首页 文章

使用TCP c#将数据包从服务器发送到特定客户端

提问于
浏览
0

我目前正在编写客户端 - 服务器应用程序 . 客户端在尝试定位服务器时发送UDP广播消息,服务器发送UDP广播消息以识别其位置 .

当客户端收到标识服务器位置的消息时,它会尝试使用socket.Connect(remoteEndPoint)连接到服务器 .

服务器在侦听套接字上侦听这些TCP请求,并使用listensocket.accept()接受请求 . 客户端详细信息存储在数组中(包括其IP和端口号)

客户端向服务器发送一条消息,其中包含用户输入的用户名和密码的信息 .

服务器检查数据库中的用户名和密码,并根据结果将TCP消息(这是它中断的位置)发送回发送请求以使用侦听套接字检查U&P的客户端 . 我试图使用下面的代码发送TCP消息,但它不会工作,因为我收到一个错误 .

TCPSocket.SendTo(message, clientsArray[i].theirSocket.RemoteEndPoint);

2 回答

  • 0

    我不确定你使用的是什么方法 .

    但在C#中有2个可用作服务器的常用类:TcpClientSocket

    TcpClient

    ...
    //Start Server
    Int32 port = 13000;
    IPAddress localAddr = IPAddress.Parse("127.0.0.1");
    server = new TcpListener(localAddr, port);
    server.Start();
    
    //Accept Client
    TcpClient client = server.AcceptTcpClient();            
    
    NetworkStream stream = client.GetStream();
    String data = "Message From Server";
    byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);
    
    //Send to Client
    stream.Write(msg, 0, msg.Length);
    ...
    

    并在 Socket using TCP

    ...
    //Start Server
    Socket listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    IPAddress hostIP = (Dns.Resolve(IPAddress.Any.ToString())).AddressList[0];
    IPEndPoint ep = new IPEndPoint(hostIP, port);
    listenSocket.Bind(ep); 
    listenSocket.Listen(backlog);
    
    //Accept Client
    Socket handler = listener.Accept();
    
    String data = "Message From Server";
    byte[] msg = Encoding.ASCII.GetBytes(data);
    
    //Send to Client
    handler.Send(msg);
    ...
    

    并在 Socket using UDP

    You shouldn't use this on your server since you are using TCP

    ...
    IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName());
    IPEndPoint endPoint = new IPEndPoint(hostEntry.AddressList[0], 11000);
    
    Socket s = new Socket(endPoint.Address.AddressFamily, SocketType.Dgram, ProtocolType.Udp);
    
    String data = "Message From Server";
    byte[] msg = Encoding.ASCII.GetBytes(data);
    //Send to Client by UDP
    s.SendTo(msg, endPoint);
    ...
    
  • 3

    通常,当您从客户端获得连接时,您将获得TcpClient . 该类有一个方法GetStream() . 如果您想将一些数据发送到该客户端,只需将所需数据写入该流 .

相关问题