Sending a value from server to client with sockets

前端 未结 4 2103
情深已故
情深已故 2020-11-30 03:32

I am using the following projects in order to create an asynchronous communication between server and client sockets. When I am running those projects I am sending a message

4条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-30 03:53

    On page https://msdn.microsoft.com/en-us/library/fx6588te%28v=vs.110%29.aspx see method AcceptCallback (it's called when client connects). There is line Socket handler = listener.EndAccept(ar);. This happens for each client when it connects, so keep these Socket instances to some list. When you want to send data to clients, use Send method from that same example with each socket from list (or selectively if you want to send only to some clients).

    private static void Send(Socket handler, String data) {
        // Convert the string data to byte data using ASCII encoding.
        byte[] byteData = Encoding.ASCII.GetBytes(data);
    
        // Begin sending the data to the remote device.
        handler.BeginSend(byteData, 0, byteData.Length, 0,
            new AsyncCallback(SendCallback), handler);
    }
    

提交回复
热议问题