The foundation of their computer network is too poor, a very small demo incredibly engaged in a day, really drunk, but the pit tread more, nature know how to walk. First, the service-side code Class Server implements Runnable{public static void main () {thread Server = new Thread (new Server ()); Server.star T ();}
Service side because need to accept the information of multiple clients, so need to open the port waiting for the client to connect, I do not write try catch, a bit more
public void Run () while{(True) {System.out.println ("Server Start:"); /local PC port 18888ServerSocket Server = new ServerSocket (18888); socket socket = server.accept (); System.out.println ("Server Accept.."); /input stream, receiving client information BufferedReader br = new BufferedReader (New InputStreamReader (Socket.getinputstream ())); String str = br.readline (); if (str== "Exit") { socket.close ();} The output stream, sending information to the client printwriter pw = new PrintWriter (New BufferedWriter (Socket.getoutputstream ())), true);p w.println (str);//finally do not forget to close the processing stream pw.close (); Br.close (); Finally{if (Null!=socket) socket.close ();
And then there's the code for the Android side
Control get I will not list, only a edittext and Button,button click, the content of EditText to the server Btnsend.setonclicklistener (new Onclicklistener () {/ /note Here the IP address socket socket = new Socket ("10.0.2.2", 18888); Input stream, accept server-side information BufferedReader br = new BufferedReader (New InputStreamReader (Socket.getinputstream ())); String str = br.readline (); if (null!=str) {edittext.settext (str);} Output stream, sending information to the server PrintWriter pw = new PrintWriter (New BufferedWriter (Socket.getoutputstream ())), true);p w.println (str);//finally do not forget to close the processing stream br.close ();p w.close (); if (socket!=null) {socket.close ();}
over~
The code originates from the original author
Enter the link description here
Summarize the pits I encountered:
- Networking permissions. Use the socket to connect to the server, you need Android Internet permissions, this do not forget.
- Server-side IP address. If it is connected to the PC with the simulator, the Android IP is "10.0.2.2", the port needs to find the port of the PC is not occupied (otherwise you will encounter "Address already in Use:jvm_bind" problem), with the real machine, You need to determine the local IP (console input ipconfig) on your computer.
- The opening of the stream is off.
On the whole, it's a pretty simple demo, but I'm getting complicated.
Android connects to server via socket (PC side)