好的,所以我的一个朋友正在教我有关 java 的网络知识,我们有一个成功的程序。这是一个简单的聊天,我们用 putty 连接,但我们有一个问题。一次只能连接一个客户端。有人可以说如何一次连接更多客户端以及如何限制连接的客户端数量吗?
public class Base
{
static ServerSocket serverSocket;
public static void main(String[] args) throws IOException
{
final ServerSocket serverSocket = new ServerSocket (1337);
Thread thread = new Thread(new Runnable()
{
public void run()
{
try
{
System.out.println("Waiting for connections...");
//Make Socket on port
Socket client = serverSocket.accept();
System.out.println("Connection from " + client.getInetAddress());
//initialixe no socket with connect server gets
BufferedReader in = new BufferedReader (new InputStreamReader(client.getInputStream()));
//init new beffer to read incom
//while loop to read stuff
final BufferedWriter out = new BufferedWriter(new PrintWriter(client.getOutputStream()));
out.write("Your Connected Mate");
out.newLine();
out.flush();
new Thread(new Runnable()
{
public void run()
{
try
{
Scanner s = new Scanner(System.in);
while(s.hasNext())
{
out.write("CLIENT] " + s.nextLine());
out.newLine();
out.flush();
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}).start();
while(true)
{
//make a string form anything thats read from the socket
String tmp = in.readLine();
//if the string isnt null (which it is if we disconnect) print it out
if(tmp != null)
{
System.out.println("[CLIENT -> SERVER] " + tmp);
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
});
thread.run();
}
}
我们没有尝试过任何事情,因为我们不知道:)