2013-10-05 40 views
1

我對聯網和使用網絡通過編程發送消息非常陌生。無論如何,我有一個客戶端和服務器的Java命令行應用程序(服務器運行在同一臺機器上的虛擬機上,使用橋接網絡適配器,主機到客戶機ping工作,反之亦然),它會出現在服務器端它收到的消息來自不同的端口。這是正常的行爲嗎?機器用完端口後會發生什麼? Java的庫是否在完成後智能地關閉端口?Java和TCP消息 - 每次在不同端口上發送消息

所以基本上,這是一個問題嗎?如果是這樣,我該如何解決它? 從服務器輸出,然後代碼爲下面列出的客戶端

服務器輸出之後,發送一些信息:

Received (/192.168.1.122:59628): shsfh 

Received (/192.168.1.122:59629): dfsh 

Received (/192.168.1.122:59631): dfh 

Received (/192.168.1.122:59632): fdshdf 

Received (/192.168.1.122:59633): shf 

Received (/192.168.1.122:59637): fgfggsdfhsfdh 

Received (/192.168.1.122:59638): fdshf 

Received (/192.168.1.122:59639): hs 

Received (/192.168.1.122:59640): hfh 

代碼,客戶端發送這些消息:

import java.io.*; 
import java.util.*; 
import java.net.*; 
class TCPClient 
{ 
    public static void main(String argv[]) throws Exception 
    { Scanner scan = new Scanner(System.in); 
     while (true) 
     { 
      String msgcont = scan.nextLine(); 
      System.out.println(tcpSend("192.168.1.153", 6789, 5000, msgcont)); 
     } 
    } 

public static String tcpSend(String ip, int port, int timeout, String content) 
{ 
    String ipaddress = ip; 
    int portnumber = port; 
    String sentence; 
    String modifiedSentence; 
    Socket clientSocket; 
    try 
    { 
     clientSocket = new Socket(ipaddress, portnumber); 
     DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream()); 
     BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); 
     outToServer.writeBytes(content + '\n'); 
     clientSocket.setSoTimeout(timeout); 
     modifiedSentence = inFromServer.readLine(); 
     clientSocket.close(); 
      outToServer.close(); 
     inFromServer.close(); 
    } 
    catch (Exception exc) 
    { 
      modifiedSentence = ""; 
    } 
      return modifiedSentence; 
} 
} 
+0

您正在爲發送的每條評論創建一個新連接,因此它將位於不同的端口上。如果每次使用相同的連接,效率會提高100倍,並且每次都使用相同的端口。 –

+0

感謝彼得和neeagl的快速和有用的迴應。他們都很有幫助。 –

回答

1

是,每次你打開一個套接字到其他主機,連接可以啓動從您計算機上的任何其他端口。操作系統選擇下一個可用端口並建立連接。

有65536個可用的開放端口,系統保留了第一個端口1-1024個端口。

+1

+1從技術上講,第一個~48K被保留用於不同的目的,「49152-65535」對於臨時端口是空閒的,但Linux不會使用第一個1024,除非你是root用戶。 Windows並不那麼嚴格。 http://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers –

+1

如果您不是root用戶,則可以使用1024,但不能使用1023。 –