In fact, a simple analysis, you can see the customer and service communication is the main channel is the socket itself, and the server through the Accept method is to agree to establish communication with customers. This way when the client establishes the socket. The server also uses this link to communicate, so as long as we have more than one connection. Then our program can be changed to the following:
So the question below is how to use threads. The first thing to do is to create threads and make them accessible to network connections. The thread then executes the action just now, to create the thread either to inherit thread directly or to implement the Runnable interface. To establish a connection to the socket, just pass the reference. and to execute the thread you have to rewrite the Run method, and the Run method does what the single threaded version main does, so our program becomes this:
import java.net.*;
Import java.io.*;
public class multiuser extends thread{
Private Socket client;
Public multiuser (Socket c) {
This.client=c;
public void Run () {
try{
BufferedReader in=new bufferedreader (New InputStreamReader (client.getinputstr EAM ()));
PrintWriter out=new PrintWriter (Client.getoutputstream ());
//mutil User but can parallel
while (true) {
String str=in.readline ();
System.out.println (str);
Out.println ("has receive ...");
Out.flush ();
if (str.equals ("End")
break;
}
Client.close ();
}catch (IOException ex) {
}finally{
}
}
public static void Main (string[] args) throws Ioexcept ion{
ServerSocket server=new serversocket (5678);
while (true) {
//transfer location change single user or Multi User
multiuser mu=new multiuser (server.accept ());
Mu.start ();
}
}
}
Client code:
import Java.net.*;
import Java.io.*;
public class Client{
static Socket Server;
public static void main(String[] args) throws Exception
{
Server=new Socket (InetAddress.getLocalHost(),5678);
BufferedReader in=new BufferedReader(new InputStreamReader(Server.getInputStream()));
PrintWriter out=new PrintWriter(Server.getOutputStream());
BufferedReader wt=new BufferedReader(new InputStreamReader(System.in));
while(true)
{
String str=wt.readLine();
out.println(str);
out.flush();
if(str.equals("end"))
{
break;
}
System.out.println(in.readLine());
}
Server.close();
}
}
This program accepts the client's keyboard input and outputs the information to the server. and put "end" as an exit command.
The above program completes the simple communication between the two computers.