简体   繁体   中英

Java and TCP messages - messages sending on different ports each time

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

Yes, everytime you open a socket to other host, the connection can be initiated from any of the remaining port on your machine. The OS chooses the next available port and makes the connection.

There are 65536 open ports available from which first 1-1024 ports are reserved by the system.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM