मेरे पास एक टीसीपी सर्वर क्लास है जो अच्छी तरह से एक टीसीपी सर्वर की तरह कार्य करता है। आप नीचे दिए गए वर्ग पा सकते हैं:दो अलग-अलग सॉकेट उदाहरण एक ही टीसीपी पोर्ट (पोर्ट पहले से उपयोग में) सुन सकते हैं
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;
}
}
और मैं एक कोड टुकड़ा है कि इस करता है:
TcpServer tcpServer = new TcpServer(LocalPort);
while(1)
{
tcpServer.accept();
Thread thread = new Thread(new runnable(tcpServer));
thread.start();
tcpServer = new TcpServer(LocalPort);
}
हालांकि मैं एक बंदरगाह पहले से ही हो रही है उपयोग में त्रुटि। मैंने सोचा कि दो अलग सॉकेट उदाहरण उसी बंदरगाह को सुन सकते हैं क्योंकि मल्टीप्लेक्सिंग एक ही बंदरगाह के माध्यम से दो कनेक्शन की अनुमति देता है जब कनेक्टर के पास अलग-अलग आईपी या पोर्ट होता है? मुझे क्या याद आ रही है?
नहीं, आप पहले से ही सुनने वाले राज्य में बंदरगाह का उपयोग नहीं कर सकते हैं। हालांकि किसी भी संख्या में ग्राहक इस पोर्ट से जुड़ सकते हैं। – m0skit0