简体   繁体   English

一台服务器中的Java TCP和UDP回显

[英]Java TCP and UDP echo in one server

I am trying to build a server which can echo the input from either a TCP or a UDP client. 我正在尝试构建一个服务器,该服务器可以回显来自TCP或UDP客户端的输入。

So far the best I could come up with is this: 到目前为止,我能想到的最好的办法是:

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

public class EchoServerMultiProtocol {
    public static void main(String[] args) throws IOException {

        String clientSentence;
        String capitalizedSentence;

        while (true) {
            /*******************************************************************
             * * Handle TCP * *
             *******************************************************************/
            ServerSocket TCP_Socket = new ServerSocket(6789);

            Socket connectionSocket = TCP_Socket.accept();

            BufferedReader inFromClient = new BufferedReader(
                    new InputStreamReader(connectionSocket.getInputStream()));

            DataOutputStream outToClient = new DataOutputStream(
                    connectionSocket.getOutputStream());

            clientSentence = inFromClient.readLine();

            capitalizedSentence = clientSentence.toUpperCase() + '\n';

            outToClient.writeBytes(capitalizedSentence);

            /*******************************************************************
             * * Handle UDP * *
             *******************************************************************/
            DatagramSocket UDP_Socket = new DatagramSocket(9876);

            byte[] receiveData = new byte[1024];
            byte[] sendData = new byte[1024];

            DatagramPacket receivePacket = new DatagramPacket(receiveData,
                    receiveData.length);

            UDP_Socket.receive(receivePacket);

            clientSentence = new String(receivePacket.getData());

            InetAddress IPAddress = receivePacket.getAddress();

            int port = receivePacket.getPort();

            capitalizedSentence = clientSentence.toUpperCase();

            sendData = capitalizedSentence.getBytes();

            DatagramPacket sendPacket = new DatagramPacket(sendData,
                    sendData.length, IPAddress, port);

            UDP_Socket.send(sendPacket);

        }
    }
}

What happens is that if I send a message from the TCP client the program works as expected but from the UDP client nothing happens. 发生的情况是,如果我从TCP客户端发送消息,则程序按预期运行,但从UDP客户端没有任何反应。 I'm not very well versed in client/server communication so any help would be appreciated. 我不太熟悉客户端/服务器通信,因此将不胜感激。

The client codes are below but I doubt they are the source of the problem. 客户代码在下面,但我怀疑它们是问题的根源。

TCP Client TCP客户端

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

class EchoClientTCP {

    public static void main(String argv[]) throws Exception {
        String sentence;
        String modifiedSentence;

        BufferedReader inFromUser = new BufferedReader(new InputStreamReader(
                System.in));

        Socket clientSocket = new Socket("127.0.0.1", 6789);

        DataOutputStream outToServer = new DataOutputStream(
                clientSocket.getOutputStream());

        BufferedReader inFromServer = new BufferedReader(new InputStreamReader(
                clientSocket.getInputStream()));

        sentence = inFromUser.readLine();

        outToServer.writeBytes(sentence + '\n');

        modifiedSentence = inFromServer.readLine();

        System.out.println("FROM SERVER: " + modifiedSentence);

        clientSocket.close();

    }
}

UDP Client UDP客户端

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

class EchoClientUDP {
    public static void main(String args[]) throws Exception {

        BufferedReader inFromUser = new BufferedReader(new InputStreamReader(
                System.in));

        DatagramSocket clientSocket = new DatagramSocket();

        InetAddress IPAddress = InetAddress.getByName("127.0.0.1");

        byte[] sendData = new byte[1024];
        byte[] receiveData = new byte[1024];

        String sentence = inFromUser.readLine();

        sendData = sentence.getBytes();

        DatagramPacket sendPacket = new DatagramPacket(sendData,
                sendData.length, IPAddress, 9876);

        clientSocket.send(sendPacket);

        DatagramPacket receivePacket = new DatagramPacket(receiveData,
                receiveData.length);

        clientSocket.receive(receivePacket);

        String modifiedSentence = new String(receivePacket.getData());

        System.out.println("FROM SERVER:" + modifiedSentence);

        clientSocket.close();

    }
}

Thank you for your help. 谢谢您的帮助。

Your program blocks waiting for a TCP message, so it never sees any UDP. 您的程序阻止等待TCP消息,因此它永远不会看到任何UDP。

You will need, at least, two threads, one for each. 您至少需要两个线程,每个线程一个。

Accept is a blocking call. 接受是阻止呼叫。 It never gets to the part of the code with the UDP socket. 它永远不会通过UDP套接字到达代码的一部分。

Please just make your life easy and use Netty . 请让您的生活更轻松,并使用Netty In a couple of lines of code you have an efficient thread model, support for most common protocols and a great framework to handle messages. 在几行代码中,您有一个有效的线程模型,对大多数常用协议的支持以及一个很好的处理消息的框架。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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