Tôi có một lớp TcpServer chịu trách nhiệm, hoạt động như một máy chủ tcp. Bạn có thể tìm thấy những lớp dưới đây:Hai thể hiện ổ cắm khác nhau có thể nghe cùng một cổng TCP (Cổng đã được sử dụng) hay không
public class TcpServer {
private ServerSocket serverSocket;
private Socket socket;
private int locallyBoundPort;
public TcpServer() {
}
public TcpServer(int locallyBoundPort) {
try {
this.serverSocket = new ServerSocket(locallyBoundPort);
serverSocket.setReuseAddress(true);
} catch (IOException e) {
System.out.println("Error at binding to port TCP : " + locallyBoundPort + "...cause : " + e.getMessage());
}
socket = null;
}
public void accept() {
try {
socket = serverSocket.accept();
socket.setReuseAddress(true);
} catch (IOException e) {
System.out.println("Error at accept : " + locallyBoundPort);
}
}
public void send(Data data) throws IOException {
if(socket != null) {
ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
out.writeObject(data);
}
}
public Data receive() throws ClassNotFoundException, IOException {
if(socket != null) {
ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
return (Data) in.readObject();
} else {
return null;
}
}
public boolean bind(int port) throws IOException {
try {
this.serverSocket = new ServerSocket(port);
this.locallyBoundPort = port;
} catch(IOException e) {
return false;
}
return true;
}
public void close() {
try {
serverSocket.close();
socket.close();
} catch (IOException e) {
OzumUtils.print("IOException in close, TcpServer");
}
}
public int getLocallyBoundPort() {
return locallyBoundPort;
}
public Socket getSocket() {
return socket;
}
public ServerSocket getServerSocket() {
return serverSocket;
}
}
Và tôi có một mảnh mã mà thực hiện điều này:
TcpServer tcpServer = new TcpServer(LocalPort);
while(1)
{
tcpServer.accept();
Thread thread = new Thread(new runnable(tcpServer));
thread.start();
tcpServer = new TcpServer(LocalPort);
}
Tuy nhiên tôi nhận được một cổng đã do lỗi sử dụng. Tôi nghĩ rằng hai trường hợp ổ cắm khác nhau có thể nghe cùng một cổng như ghép kênh cho phép hai kết nối thông qua cùng một cổng khi kết nối có ip hoặc cổng khác nhau? Tôi đang thiếu gì?
Không, bạn không thể sử dụng cổng đã ở trạng thái nghe. Tuy nhiên, bất kỳ số lượng khách hàng nào cũng có thể kết nối với cùng một cổng này. – m0skit0