Java多個客戶端同時連接服務端,在現實生活中用得比較多。同時執行多項任務,第一想到的當然是多線程了。下面用多線程來實現並發多連接。
import Java.net.*;
import Java.io.*;
public class ThreadServer extends Thread
{
private Socket clIEnt;
public ThreadServer(Socket c)
{
this.clIEnt=c;
}
public void run()
{
try
{
BufferedReader in=new BufferedReader(new InputStreamReader(clIEnt.getInputStream()));
PrintWriter out=new PrintWriter(clIEnt.getOutputStream());
//Mutil User but can't 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 IOException
{
ServerSocket server=new ServerSocket(8000);
while (true)
{
//transfer location change Single User or Multi User
ThreadServer mu=new ThreadServer(server.accept());
mu.start();
}
}
}