[英]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.