C++ socket server receives a standard message from my C++ client without any issue. Now I'm trying to write the client in C# and it connects without any issue.
My problem comes in when I try to send a simple message from the C# client to the C++ server. Through a bit of research I think C++ is expecting a buffer that's 255 in length and it's just not outputting the message because it doesn't know how long the message is but I'm not sure how to communicate that using C#.
C++ Server reads data from each client on a separate thread as follows.
void Socket::thread (int newsockfd) {
char buffer[256];
int n;
std::cout << "Waiting to read client messages\n";
n = read(newsockfd,buffer,255);
if (n < 0){
std::cout << "Failed to read from socket\n";
return;
}
printf("Received Message %s",buffer);
}
C# Client sends data to the server as follows.
try {
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Connect(endpoint);
NetworkStream stream = new NetworkStream(socket, true);
if (stream.CanWrite){
byte[] message = Encoding.UTF8.GetBytes("Hello World");
stream.Write(message, 0, message.Length);
Debug.Log("Wrote message to stream with " + message.Length.ToString() + " length.");
}
stream.Close();
socket.Close();
} catch (SocketException e) {
Debug.Log("Socket exception: " + e);
}
Everything works totally fine, the connection gets made successfully but no message ever goes through so I think that the message is probably being written successfully but C++ doesn't know when to stop reading.
For the record, here's how the C++ client sends its message (just a shorter excerpt).
char buffer[256];
bzero(buffer,256);
fgets(buffer,255,stdin);
n = write(sockfd,buffer,strlen(buffer));
if (n < 0)
std::cout << "Error writing to socket\n";
close(sockfd);
Which works totally fine and sends the message as expected. I'm really just having trouble with the juxtaposition of C++ and C# I guess. I'm happy to provide anymore information if needed :)