[英]How to use source port to send and receive data by TCP/IP in Java
I have started a client in my system. 我已经在系统中启动了一个客户端。 It is running on port no 7913. I am sending a request data via TCP/IP from Java to server socket running on 7913.
它在端口7913上运行。我正在通过TCP / IP从Java向在7913上运行的服务器套接字发送请求数据。
log is Message sent to Socket [addr=/190.161.153.109,port=7913,localport=54717]
日志是发送到套接字的消息[addr = / 190.161.153.109,port = 7913,localport = 54717]
I have also received the response from server for that particular data. 我还收到了服务器对特定数据的响应。 Now the server is also trying to send a request to my localport 54717, not to port where my application is listening [ie 7913].
现在,服务器还尝试将请求发送到我的本地端口54717,而不是发送到我的应用程序正在侦听的端口[即7913]。
How to handle the request? 如何处理要求? When I try to connect with telnet to my localport, connection is refused.
当我尝试使用telnet连接到本地端口时,连接被拒绝。
The code: 编码:
public static String ickTransport(String ickHeader,String ickdata, Socket connection) throws UnknownHostException, IOException
try
{
connection.setSoTimeout(Integer.parseInt(ickTimeOut));
log.debug("ick Message for "+connection.toString()+" is " + ickMessage);
BufferedOutputStream bos = new BufferedOutputStream(connection.getOutputStream());
DataOutputStream osw = new DataOutputStream(bos);
osw.writeShort(Integer.parseInt(ickHeader));
osw.writeBytes(ickMessage);
osw.flush();
DataInputStream stream = new DataInputStream(connection.getInputStream());
int numberRecords = stream.readShort();
if (numberRecords > 0) {
int nSizeRead = 0;
byte[] bRequest = new byte[numberRecords];
int nSizeBuffer;
for (; numberRecords > 0; numberRecords -= nSizeBuffer) {
byte[] bBuffer = new byte[numberRecords];
nSizeBuffer = stream.read(bBuffer);
System.arraycopy(bBuffer, 0, bRequest, nSizeRead, nSizeBuffer);
nSizeRead += nSizeBuffer;
}
ickResponse = new String(bRequest);
log.debug("Response from ick is " + ickResponse);
}
}
catch (SocketTimeoutException e)
{
log.error(e.getMessage());
}
return ickResponse;
To understand what is going on you should understand what is listen socket and how it differs from connection socket . 要了解发生了什么,您应该了解什么是监听套接字以及它与连接套接字有何不同。
When your application listens it (this ServerSocket
does): 当您的应用程序监听它时(此
ServerSocket
会监听):
bind
request or in constructor bind
请求或构造函数中指定的端口 accept
method. accept
方法为新连接提供新的套接字。 When your application establishes NEW connection it use connect
method. 当您的应用程序建立NEW连接时,将使用
connect
方法。 Unless you use bind
request on socket it: 除非您在套接字上使用
bind
请求,否则:
Because nobody listens this dynamic port telnet requests are refused on it. 因为没有人监听此动态端口telnet请求,所以拒绝了它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.