通过UDP和TCP发送和接收文本消息

时间:2019-05-21 14:14:14

标签: java tcp udp

我想创建一个代码,该代码使用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

以上两个代码通过使用IP地址和端口号从客户端向服务器发送消息来启用TCP。客户端和服务器的代码是隔离的。

我们有两个客户和相同的代码。他们可以发送和接收UDP格式的文本消息,以及一台服务器和客户端之间以TCP格式的文本消息。

0 个答案:

没有答案