1

I've very new to networking and using networks to send messages through programming. Anyways, I have a client and server java command line application (server is running in a VM on the same machine with a bridged network adapter, and host to guest pinging works and vice versa), and it would appear on the server side that each message it receives is coming from a different port. Is this normal behavior? What happens when the machine runs out of ports to use? Does Java's libraries intelligently close the ports after it's done with them?

So basically, is this even a problem? If it is, how do I go about fixing it? Output from the server and then code for the client listed below.

SERVER OUTPUT AFTER SENDING SOME MESSAGES:

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

CODE FOR THE CLIENT THAT SENT THOSE MESSAGES:

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;
}
}
4

1 回答 1

1

是的,每次您打开到其他主机的套接字时,都可以从您机器上的任何剩余端口启动连接。操作系统选择下一个可用端口并建立连接。

有 65536 个可用的开放端口,其中前 1-1024 个端口由系统保留。

于 2013-10-05T19:19:30.137 回答