5
I’m taking a look at an example of microsoft itself and I’m having some doubts.
Example taken from this link: https://msdn.microsoft.com/pt-br/library/bew39x2a(v=vs.110). aspx
Let’s imagine a chat environment via socket... Should I establish a socket connection whenever sending a message? Follows the method of example:
private static void StartClient()
{
// Connect to a remote device.
try
{
// Establish the remote endpoint for the socket.
// The name of the
// remote device is "host.contoso.com".
IPHostEntry ipHostInfo = Dns.GetHostEntry("127.0.0.1");
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);
// Create a TCP/IP socket.
Socket client = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
// Connect to the remote endpoint.
client.BeginConnect(remoteEP,
new AsyncCallback(ConnectCallback), client);
connectDone.WaitOne();
// Send test data to the remote device.
Send(client, "This is a test<EOF>");
sendDone.WaitOne();
// Receive the response from the remote device.
Receive(client);
receiveDone.WaitOne();
// Write the response to the console.
Console.WriteLine("Response received : {0}", response);
// Release the socket.
client.Shutdown(SocketShutdown.Both);
client.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
In this example is created the connection, and sent a message, then awaits the return of the message and finally closes the connection.
Can I keep one connection open and send multiple messages separately?
In the case of sendDone.WaitOne()
, what in fact this method does?
When I run the communication on a separate thread, it works perfectly but when executing the command on the main thread the project gets stuck, as if it was waiting for a return (which by the way never arrives rsrs)
In the case below I have a method that sends the information to the socket connection:
client.BeginSend(byteData, 0, byteData.Length, 0,
new AsyncCallback(SendCallback), client);
where client
is the type Socket
;
byteData
represents the information I am sending, which is the best way to convert an object with values to byte and server side byte converter for the same object type?
my initial intention is to make a communicator, like a chat server, where there would be rooms and groups. In this case every client should also be a server to always listen to the server messages?
In the client I can create a thread that will be exclusive to "listen" and perform the tasks according to the return?
If you have any educational material that addresses these and more details let me know :))