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();
}
}
}