我有两个java类,一个用于服务器,一个用于客户端。使用常规套接字在它们之间建立连接。如何使用多线程允许客户端类的许多实例同时连接到服务器? 我尝试搜索SO,但我找不到任何简洁明了的答案。
以下是我的重要方法(两者都在Server类中):
public void startRunning() {
try {
server = new ServerSocket(portNum, 10); // port num and backlog
while (true) {
try {
waitForConnection();
setupStreams(); //sets up streams
whileChatting(); //exchanges messages
} catch (EOFException e1) {
showMessage("\n Server ended the connection");
} finally {
closeEverything(); //closes all streams
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
private void waitForConnection() throws IOException {
showMessage(" Waiting for connections...\n");
connection = server.accept();
showMessage(" Connected to "
+ connection.getInetAddress().getHostName());
}
答案 0 :(得分:2)
这是一个简单的例子。新的Thread回复每个新传入的客户端。
import java.io.*;
import java.net.*;
class Server implements Runnable {
public static final int port = 5678;
public void run() {
try{
ServerSocket server = new ServerSocket(port);
while (true)
{
final Socket client = server.accept();
new Thread() {
public void run() {
try{
ObjectInputStream in =
new ObjectInputStream( client.getInputStream() );
String msg = (String) in.readObject();
System.out.println(msg);
}
catch(Exception e){System.err.println(e);}
}}.start();
}
}
catch(IOException e){System.err.println(e);}
}
}
class Client {
public void writeMessage(String msg) throws IOException {
new ObjectOutputStream((new Socket("localhost",Server.port).getOutputStream())).writeObject(msg);
}
}
public class ClientServer{
public static void main(String[] args) throws IOException{
Server server = new Server("My Multithreaded Server");
new Thread(server).start();
Client client1 = new Client();
Client client2 = new Client();
client1.writeMessage("Hello !");
client2.writeMessage("Give me five !");
}
}