1. First establish WiFi hotspot server WiFi Client connection
2. Turn on a sub-thread to loop through a port for data flow input and output
/* Server receives data */
Class Receiver extends Thread {
Public String receivercontent;
public Boolean flag = true;
Public ServerSocket serversocket = null;
public void Run () {
try {
//create ServerSocket
ServerSocket = new ServerSocket (3358);
while (flag) {
//Accept client requests
Socket clients = serversocket.accept ();
System.out.println ("accept");
try {
//Receive client message
BufferedReader in = new BufferedReader (
New InputStreamReader (Client.getinputstream ())) ;
Receivercontent = In.readline ();
System.out.println ("read:" + receivercontent);
Handler.sendemptymessage (0);
//Send a message to client
PrintWriter out = new PrintWriter (
New BufferedWriter (New OutputStreamWriter (
Client.getoutputstream ())), true);
Out.println ("Server Message");
//Close stream
Out.close ();
In.close ();
} catch (Exception e) {
System.out.println (e.getmessage ());
E.printstacktrace ();
} finally {
//close
Client.close ();
System.out.println ("close");
}
}
} catch (Exception e) {
System.out.println (e.getmessage ());
}
}
public void Close () {
Flag = false;
if (serversocket! = null) {
try {
Serversocket.close ();
} catch (IOException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}
}
}
/* Client sends data */
Class Sender extends Thread {
String ServerIP;
String message;
Sender (string serveraddress, String message) {
Super ();
ServerIP = serveraddress;
this.message = message;
}
public void Run () {
Socket sock = null;
PrintWriter out;
try {
Declares the sock, where the parameter is the IP address of the server and the custom port
Sock = new Socket (ServerIP, 3358);
LOG.W ("Wificonnection", "I am try to writer" + sock);
} catch (Unknownhostexception e) {
TODO auto-generated Catch block
E.printstacktrace ();
} catch (IOException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
try {
Send messages to server side
out = new PrintWriter (New BufferedWriter (
New OutputStreamWriter (Sock.getoutputstream ())), true);
OUT.PRINTLN (message);
Receiving messages from the server side
BufferedReader br = new BufferedReader (New InputStreamReader (
Sock.getinputstream ()));
String msg = Br.readline ();
Message m = Handler.obtainmessage ();
M.what = 1;
M.obj = msg;
Handler.sendmessage (m);
Close the stream
Out.close ();
Out.flush ();
Br.close ();
Close socket
Sock.close ();
} catch (Exception e) {
LOGUTIL.E ("Send error: [Sender]run ()" + e.getmessage ());
}
}
}
Android WiFi hotspot Socket communication