[英]How to use source port to send and receive data by TCP/IP in Java
我已经在系统中启动了一个客户端。 它在端口7913上运行。我正在通过TCP / IP从Java向在7913上运行的服务器套接字发送请求数据。
日志是发送到套接字的消息[addr = / 190.161.153.109,port = 7913,localport = 54717]
我还收到了服务器对特定数据的响应。 现在,服务器还尝试将请求发送到我的本地端口54717,而不是发送到我的应用程序正在侦听的端口[即7913]。
如何处理要求? 当我尝试使用telnet连接到本地端口时,连接被拒绝。
编码:
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;
要了解发生了什么,您应该了解什么是监听套接字以及它与连接套接字有何不同。
当您的应用程序监听它时(此ServerSocket
会监听):
bind
请求或构造函数中指定的端口 accept
方法为新连接提供新的套接字。 当您的应用程序建立NEW连接时,将使用connect
方法。 除非您在套接字上使用bind
请求,否则:
因为没有人监听此动态端口telnet请求,所以拒绝了它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.