简体   繁体   English

用于数据报类型套接字的ServerSocket吗?

[英]ServerSocket for datagram type socket?

I have a ftp client-server program which currently uses TCP. 我有一个ftp客户端服务器程序,当前使用TCP。 I need to now make it work using UDP, so using datagram sockets instead. 我现在需要使用UDP使其工作,因此请改用数据报套接字。

They way it was working was to create a ServerSocket which would listen for a connection, then give that connection to a Socket , and start a separate thread for that socket. 他们的工作方式是创建一个ServerSocket ,它将监听连接,然后将该连接提供给Socket ,并为该套接字启动一个单独的线程。

But now using DatagramSocket , there's no equivalent DatagramServerSocket, so I've no idea how I can give clients separate sockets anymore. 但是现在使用DatagramSocket ,没有等效的DatagramServerSocket,所以我不知道如何再为客户端提供单独的套接字。 Is there a server socket for datagrams? 是否有用于数据报的服务器套接字?

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

public class Server {

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

        Socket sock;
        ServerSocket servSock = new ServerSocket(4444, 600);

        while(true){
            sock = servSock.accept();
            new ClientHandler(sock).start();
        }
    }
}

Well, UDP is a connectionless protocol. 嗯,UDP是无连接协议。 Doing decent file transfer would probably mean implementing a decent chunk of TCP-like functionality. 进行体面的文件传输可能意味着实现体面的类似TCP的功能。

DatagramSocket serverSocket  = new DatagramSocket(PORT_NUMBER);`

Will act as a server socket. 将充当服务器套接字。

alternatively you could use 或者你可以使用

DatagramChannel channel = DatagramChannel.open();
channel.socket().bind(new InetSocketAddress(9999));

You don't need to give clients separate sockets. 您不需要为客户端提供单独的套接字。 You have the source address in each datagram. 您在每个数据报中都有源地址。 That tells you which client the datagram is from. 告诉您数据报来自哪个客户端。 You only need one socket in a UDP server. UDP服务器中只需要一个套接字。

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

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