First establish the server-side program:
1.myserversocket.java
Package Com.test.test;public class myServerSocket {public static void main (string[] args) {new Serverlistener (). Start ();}}
2.serverlistener.java for listening to 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=serversocket.accept (); Joptionpane.showmessagedialog (NULL, "There is a client 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 Au To-generated catch Blocke.printstacktrace ();}} public void Run () {int Count=0;while (true) {count++;out ("loop+" +count);}}}
Run Myserversocket.java:
Open DOS interface input telnet localhost 12345 display
Click OK below:
Then open a client input command:
It can be seen that each client has a separate thread to handle.
android--Creating a network chat room using socket communication 1