Information interaction between Android sockets

Source: Internet
Author: User

Create a Java Project

Socketserver.java

Import Java.net.ServerSocket;
Import Java.net.Socket;
Import java.util.ArrayList;
Import java.util.List;

public class Socketserver {

private static ServerSocket serivce;

  

public static void Main (string[] args) throws IOException {

Socket1 ();
}
public static void Socket1 () throws ioexception{
Serivce = new ServerSocket (30000);
while (true) {
Waiting for client connections
Socket socket = serivce.accept ();
New Thread (new androidrunable (socket)). Start ();
}
}

}

Create a usage thread

Androidrunable.java

Package cn.socket.server;

Import Java.io.BufferedReader;
Import java.io.IOException;
Import Java.io.InputStream;
Import Java.io.InputStreamReader;
Import Java.io.OutputStream;
Import Java.net.Socket;

public class Androidrunable implements runnable{
Socket socket = NULL;

Public androidrunable (socket socket) {
This.socket = socket;
}

@Override
public void Run () {
Output Hello Worild to Android client
String line = null;
InputStream input;
OutputStream output;
String str = "Hello!" Hello word ";
try {
Send a message to the client
Output = Socket.getoutputstream ();
input = Socket.getinputstream ();
BufferedReader BFF = new BufferedReader (
New InputStreamReader (input));
Output.write (Str.getbytes ("UTF-8")); This encoding format can be used GBK
Output.flush ();
Half-closed socket
Socket.shutdownoutput ();
Get information about a client
while (line = Bff.readline ()) = null) {
System.out.print ("\ n" +line);
}
Turn off the input and output stream
Output.close ();
Bff.close ();
Input.close ();
Socket.close ();

} catch (IOException e) {
E.printstacktrace ();
}
}

}

Click Run Java

Create an Android project

Mainactivity.java

Package Com.example.socketan;

Import Java.net.Socket;

Import android.app.Activity;
Import Android.os.Bundle;
Import Android.os.Handler;
Import Android.os.Message;
Import Android.view.View;
Import Android.widget.Button;
Import Android.widget.EditText;

public class Mainactivity extends Activity implements view.onclicklistener{
Private EditText edt_ip, Edt_socket, Edt_connect;
Private Button Btn_socket;
Private String ip= "192.168.12.6";
private int tcp=30000;
Socket socket = NULL;
String buffer = "";
String geted1;
Define a child thread to communicate with the server
Clientthread Clientthread;
Public Handler MyHandler = new Handler () {
@Override
public void Handlemessage (Message msg) {
if (msg.what = = 0x11) {
Bundle bundle = Msg.getdata ();
Edt_socket.append ("Server:" +bundle.getstring ("msg") + "\ n");
}
}

};
@Override
protected void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.activity_main);
Edt_ip = (EditText) Findviewbyid (R.ID.EDT_IP);
Edt_socket = (EditText) Findviewbyid (R.id.edt_socket);
Edt_connect = (EditText) Findviewbyid (r.id.edt_connect);
Btn_socket = (Button) Findviewbyid (R.id.btn_socket);
Btn_socket.setonclicklistener (this);
}

@Override
public void OnClick (view view) {
if (view.getid () = = R.id.btn_socket) {
geted1 = Edt_connect.gettext (). toString ();
Edt_socket.append ("Client:" +geted1+ "\ n");
The client initiates the Clientthread thread to create a network connection, reading data from the server
New MyThread (Geted1,ip,tcp,myhandler). Start ();
}

}

}

Create Android using Threads

Mythread.java

Package Com.example.socketan;

Import Java.io.BufferedReader;
Import java.io.IOException;
Import Java.io.InputStreamReader;
Import Java.io.OutputStream;
Import java.net.InetSocketAddress;
Import Java.net.Socket;
Import java.net.SocketTimeoutException;

Import Android.os.Bundle;
Import Android.os.Handler;
Import Android.os.Message;

public class MyThread extends Thread {
Private String Str,ip;
private int TCP;
Socket Socket=null;
String Buffer=null;
Private Handler MyHandler;
Public MyThread (String str,string ip,int tcp,handler myhandler) {
THIS.STR=STR;
This.ip=ip;
THIS.TCP=TCP;
This.myhandler=myhandler;
}
@Override
public void Run () {
Super.run ();
Defining messages
Message msg = new Message ();
Msg.what = 0x11;
Bundle bundle = new bundle ();
Bundle.clear ();
try {
Connect to the server and set the connection timeout to 5 seconds
Socket = new socket ();
Socket.connect (New Inetsocketaddress (IP, TCP), 5000);
Get input and output stream
OutputStream OU = Socket.getoutputstream ();
BufferedReader BFF = new BufferedReader (New InputStreamReader (
Socket.getinputstream ()));
Read Send to server information
String line = null;
Buffer= "";
while (line = Bff.readline ()) = null) {
Buffer = line + buffer;
}

Sending information to the server
Ou.write (Str.getbytes ("GBK"));
Ou.flush ();
Bundle.putstring ("msg", buffer.tostring ());
Msg.setdata (bundle);
To send a message modify a component in the UI thread
Myhandler.sendmessage (msg);
Turn off various input and output streams
Bff.close ();
Ou.close ();
Socket.close ();
} catch (Sockettimeoutexception aa) {
Connection timeout displays messages in UI interface
Bundle.putstring ("MSG", "Server Connection failed!") Please check if the network is turned on ");
Msg.setdata (bundle);
To send a message modify a component in the UI thread
Myhandler.sendmessage (msg);
} catch (IOException e) {
E.printstacktrace ();
} catch (Exception e) {
E.printstacktrace ();
}
}
}

Information interaction between Android sockets

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.