Three steps learn Java Socket Program 2

xiaoxiao2021-03-06  102

In the second step, multiple customers are connected to the actual network environment at the same time, and only one user service is not feasible. A excellent network service program must deal with the user's input information, must also be able to simultaneously respond to the connection request of multiple clients. In Java, it is very easy to achieve the above features.

Design principle:

The main program monitors a port, waiting for the customer access; constructs a thread class and prepares the session. When an Socket session is generated, this session is given to thread processing, and then the main program continues to listen. It is a good way to use the Thread class or Runnable interface.

{Implement message sharing}

import java.io *;. import java.net *;. public class Server extends ServerSocket {private static final int SERVER_PORT = 10000; public Server () throws IOException {super (SERVER_PORT); try {while (true) {Socket socket = accept (); new CreateServerThread (socket);}} catch (IOException e) {} finally {close ();}} // --- CreateServerThreadclass CreateServerThread extends Thread {private Socket client; private BufferedReader in; private PrintWriter out; public CreateServerThread (Socket s) throws IOException {client = s; in = new BufferedReader (new InputStreamReader (client.getInputStream (), "GB2312")); out = new PrintWriter (client.getOutputStream (), true); out.println ( "--- welcome ---"); start ();} public void run () {Try {string line = in.readline (); while (! Line.equals ("bye") {string msg = createMessage (LINE); OUT.PRINTLN (MSG); line = in.readline ();} out.println ("--- See you, bye! ---"); client.close ();} catch (IOException E ) {}} private string createMessage (String line) {xxxxxxxxx;}} public static void main (String [] args) throws oews oews Ception {new server ();}}

This program monitors 10000 port and handles the access to the CreateSerVerthread thread. The CreateServertHread thread accepts input and responds to customers until the client enters "BYE" and the thread ends. We can process the input in the CreateMessage method, and generate results, then return the result to the customer.

转载请注明原文地址:https://www.9cbs.com/read-97135.html

New Post(0)