Android-use socket communication to establish Network Chat Room 1, android-socket
First, create a server program:
1. MyServerSocket. java
package com.test.test;public class MyServerSocket {public static void main(String[] args) {new ServerListener().start();}}
2. ServerListener. java is used to listen for port connections
Package com. test. test; import java. io. IOException; import java.net. serverSocket; import java.net. socket; import javax. swing. JOptionPane; public class ServerListener extends Thread {public void run () {try {ServerSocket serverSocket = new ServerSocket (12345); while (true) {Socket socket Socket = serverSocket. accept (); JOptionPane. showMessageDialog (null, "a client is connected to port 12345! "); New ChatSocket (socket). start () ;}} catch (IOException e) {// TODO Auto-generated catch blocke. printStackTrace ();}}}
3. ChatSocket. java
package com.test.test;import java.io.IOException;import java.io.UnsupportedEncodingException;import java.net.Socket;public class ChatSocket extends Thread {Socket socket;public ChatSocket(Socket s){this.socket=s;}public void out(String out){try {socket.getOutputStream().write(out.getBytes("UTF-8"));} catch (UnsupportedEncodingException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}public void run() {int count=0;while(true){count++;out("loop+"+count);}}}
Run MyServerSocket. java:
Open the DOS interface and enter telnet localhost 12345.
Click OK below:
Open a client and enter the following command:
It can be seen that each client has an independent thread for processing.