Keywords: Socket serversocket multithreading Server
The main program listens to a port and waits for the client to access it. At the same time, it constructs a Thread class to take over the session. When a socket session is generated, the session is handed over to the thread for processing, and the main program continues to listen. Using the Thread class or runnable interface is a good solution.
Java source code:
Import Java. io. bufferedreader; <br/> Import Java. io. ioexception; <br/> Import Java. io. inputstreamreader; <br/> Import Java. io. printwriter; <br/> Import java.net. serversocket; <br/> Import java.net. socket; <br/> public class Server extends serversocket {<br/> Private Static final int server_port = 8888; <br/> public server () throws ioexception {<br/> super (server_port); <br/> system. out. println ("service start... "); <Br/> try {<br/> while (true) {<br/> Socket socket = accept (); <br/> New createserverthread (socket ); <br/>}< br/>}catch (ioexception e) {<br/>}finally {<br/> close (); <br/>}< br/> // --- createserverthread <br/> class createserverthread extends thread {<br/> private Socket Client; <br/> private bufferedreader in; <br/> private printwriter out; <br/> Public createserverthread (socket s) throws Io Exception {<br/> client = s; <br/> In = new bufferedreader (New inputstreamreader (client <br/>. getinputstream (), "gb2312"); <br/> out = new printwriter (client. getoutputstream (), true); <br/> out. println ("--- Welcome ---"); <br/> Start (); <br/>}< br/> Public void run () {<br/> try {<br/> string line = in. readline (); <br/> while (! Line. equals ("bye") {<br/> string MSG = createmessage (line); <br/> out. println (MSG); <br/> line = in. readline (); <br/>}< br/> out. println ("--- see you, bye! --- "); <Br/> client. close (); <br/>}catch (ioexception e) {<br/>}< br/> private string createmessage (string line) <br/> {<br/> return "server response:" + line; <br/>}< br/> Public static void main (string [] ARGs) throws ioexception {<br/> new server (); <br/>}< br/>
This program listens to port 8888 and passes the access to the createserverthread thread for running. The createserverthread thread accepts the input and returns the input to the customer until the customer inputs "bye" and the thread ends. We can process the input in the createmessage method, generate the result, and then return the result to the customer.