I'm taking a look at an example from Microsoft itself and I have some questions.
Example taken from this link: link
Let's imagine a chat environment via socket ... Should I establish a socket connection every time I send a message? Here is the sample method:
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 the connection is created, and a message is sent, then it waits for the message to return and finally closes the connection.
Can I keep an open connection and send multiple messages separately?
In the case of sendDone.WaitOne()
, what does this method actually do?
When I execute the communication on a separate thread, it works perfectly, however when executing the command on the main thread the project gets stuck, as if waiting for a return (which by the way never arrives)
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 of type Socket
;
byteData
represents the information I am sending, what is the best way to convert an object with values to byte and on the server side convert from byte to the same object type?
My initial intention is to make a communicator, like a chat server, where it would have rooms and groups. In this case should every customer also be a server to always listen to the server's messages?
In the client I can create a thread that will be unique to "listen" and execute the tasks according to the return?
If you have any educational material that addresses these and more details please inform me:))