Отправлять и получать текстовые сообщения через UDP и TCP - PullRequest
0 голосов
/ 21 мая 2019

Я хочу создать код, который использует TCP для отправки и получения текстовых сообщений и UDP для связи с сервером.Как мне изменить этот существующий код?

Это существующие модели для разработки нового клиента и сервера.

Связь на основе UDP между сервером и клиентом

Код UDP:

/**
 * This module contains the presentaton logic of an Echo Client.
 * @author M. L. Liu
 */
import java.io.*;

public class EchoClient1 {
   static final String endMessage = ".";   // If you mark a dot, the Client will shut down.
   public static void main(String[] args) {
      InputStreamReader is = new InputStreamReader(System.in);
      BufferedReader br = new BufferedReader(is);
      try {
         System.out.println("Welcome to the Echo client.\n" +
                            "What is the name of the server host?");
         String hostName = br.readLine();
         if (hostName.length() == 0) // if user did not enter a name
            hostName = "localhost";  // use the default host name
         System.out.println("What is the port number of the server host?");
         String portNum = br.readLine();
         if (portNum.length() == 0)
            portNum = "7";          // default port number=7
         EchoClientHelper1 helper = 
            new EchoClientHelper1(hostName, portNum);
         boolean done = false;
         String message, echo;
         while (!done) {
            System.out.println("Enter a line to receive an echo back from the server, "
                            + "or a single peroid to quit.");
            message = br.readLine( );
            if ((message.trim()).equals (endMessage)){
               done = true;
               helper.done( );
            }
            else {
               echo = helper.getEcho(message);
               System.out.println(echo);
            }
          } // end while
      } // end try  
      catch (Exception ex) {
         ex.printStackTrace( );
      } // end catch
   } //end main
} // end class

import java.io.*;

public class EchoServer1 {
   public static void main(String[] args) {
      int serverPort = 7;    // default port
      if (args.length == 1 )
         serverPort = Integer.parseInt(args[0]);
      try {
         // instantiates a datagram socket for both sending
         // and receiving data
       MyServerDatagramSocket mySocket = new MyServerDatagramSocket(serverPort);
         System.out.println("Echo server ready.");
         while (true) {  // forever loop
            DatagramMessage request = 
               mySocket.receiveMessageAndSender();
            System.out.println("Request received");
            String message = request.getMessage( );
            System.out.println("message received: "+ message);
            // Now send the echo to the requestor
            mySocket.sendMessage(request.getAddress( ),
               request.getPort( ), message);
           } //end while
       } // end try
        catch (Exception ex) {
          ex.printStackTrace( );
        } // end catch
   } //end main
} // end class

Вышеуказанные два кода основаны на UDP и отправляют сообщения на сервер с использованием IP-адреса и номера порта.Код для клиента и сервера изолирован.

Связь по протоколу TCP между сервером и клиентом:

// TCP code
import java.io.*;

/**
 * This module contains the presentaton logic of an Echo Client.
 * @author M. L. Liu
 */
public class EchoClient2 {
   static final String endMessage = ".";
   public static void main(String[] args) {
      InputStreamReader is = new InputStreamReader(System.in);
      BufferedReader br = new BufferedReader(is);
      try {
         System.out.println("Welcome to the Echo client.\n" +
            "What is the name of the server host?");
         String hostName = br.readLine();
         if (hostName.length() == 0) // if user did not enter a name
            hostName = "localhost";  //   use the default host name
         System.out.println("What is the port number of the server host?");
         String portNum = br.readLine();
         if (portNum.length() == 0)
            portNum = "7";          // default port number
         EchoClientHelper2 helper = 
            new EchoClientHelper2(hostName, portNum);
         boolean done = false;
         String message, echo;
         while (!done) {
            System.out.println("Enter a line to receive an echo "
               + "from the server, or a single period to quit.");
            message = br.readLine( );
            if ((message.trim()).equals (endMessage)){
               done = true;
               helper.done( );
            }
            else {
               echo = helper.getEcho( message);
               System.out.println(echo);
            }
          } // end while
      } // end try  
      catch (Exception ex) {
         ex.printStackTrace( );
      } //end catch
   } //end main
} // end class

import java.io.*;
import java.net.*;

/**
 * This module contains the application logic of an echo server
 * which uses a stream-mode socket for interprocess communication.
 * A command-line argument is required to specify the server port.
 * @author M. L. Liu
 */

public class EchoServer2 {
   public static void main(String[] args) {
      int serverPort = 7;    // default port
      String message;

      if (args.length == 1 )
         serverPort = Integer.parseInt(args[0]);       
      try {
         // instantiates a stream socket for accepting
         //   connections
       ServerSocket myConnectionSocket = 
            new ServerSocket(serverPort); 
/**/     System.out.println("Echo server ready.");  
         while (true) {  // forever loop
            // wait to accept a connection
/**/        System.out.println("Waiting for a connection.");
            MyStreamSocket myDataSocket = new MyStreamSocket
                (myConnectionSocket.accept( ));
/**/        System.out.println("connection accepted");
            // Start a thread to handle this client's sesson
            Thread theThread = 
               new Thread(new EchoServerThread(myDataSocket));
            theThread.start();
            // and go on to the next client
            } //end while forever
       } // end try
        catch (Exception ex) {
          ex.printStackTrace( );
        } // end catch
   } //end main
} // end class

Вышеприведенные два кода активируются по протоколу TCP путем отправки сообщений от клиентасервер, использующий IP-адрес и номер порта.Код для клиента и сервера изолирован.

У нас есть два клиента и один и тот же код.Они могут отправлять и получать текстовые сообщения в формате UDP и текстовые сообщения между одним сервером и клиентом в формате TCP.

...