I have python program which works perfectly for internet chatting. But program built on similar sockets in C++ do not work over internet.
Python program
import thread
import socket
class p2p:
def __init__(self):
socket.setdefaulttimeout(50)
self.port = 3000
#Destination IP HERE
self.peerId = '59.95.18.156'
#declaring sender socket
self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM )
self.socket.bind(('', self.port))
self.socket.settimeout(50)
#starting thread for reception
thread.start_new_thread(self.receiveData, ())
while 1:
data=raw_input('>')
#print 'sending...'+data
self.sendData(data)
def receiveData(self):
while 1:
data,address=self.socket.recvfrom(1024)
print data
def sendData(self,data):
self.socket.sendto(data, (self.peerId,self.port))
if __name__=='__main__':
print 'Started......'
p2p()
I want to built similar functionality in c++. I took server and client programs from MSDN. But they are working only on localhost not over internet ..
they are as follows...
Sender
#include <stdio.h>
#include "winsock2.h"
void main() {
WSADATA wsaData;
SOCKET SendSocket;
sockaddr_in RecvAddr;
int Port = 3000;
char SendBuf[3]={'a','2','\0'};
int BufLen = 3;
//---------------------------------------------
// Initialize Winsock
WSAStartup(MAKEWORD(2,2), &wsaData);
//---------------------------------------------
// Create a socket for sending data
SendSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
//---------------------------------------------
// Set up the RecvAddr structure with the IP address of
// the receiver (in this example case "123.456.789.1")
// and the specified port number.
RecvAddr.sin_family = AF_INET;
RecvAddr.sin_port = htons(Port);
RecvAddr.sin_addr.s_addr = inet_addr("59.95.18.156");
//---------------------------------------------
// Send a datagram to the receiver
printf("Sending a datagram to the receiver...\n");
sendto(SendSocket,
SendBuf,
BufLen,
0,
(SOCKADDR *) &RecvAddr,
sizeof(RecvAddr));
//---------------------------------------------
// When the application is finished sending, close the socket.
printf("Finished sending. Closing socket.\n");
closesocket(SendSocket);
//---------------------------------------------
// Clean up and quit.
printf("Exiting.\n");
WSACleanup();
return;
}
Receiver
#include <stdio.h>
#include "winsock2.h"
#include<iostream>
using namespace std;
void main() {
WSADATA wsaData;
SOCKET RecvSocket;
sockaddr_in RecvAddr;
int Port = 3000;
char RecvBuf[3];
int BufLen = 3;
sockaddr_in SenderAddr;
int SenderAddrSize = sizeof(SenderAddr);
//-----------------------------------------------
// Initialize Winsock
WSAStartup(MAKEWORD(2,2), &wsaData);
//-----------------------------------------------
// Create a receiver socket to receive datagrams
RecvSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
//-----------------------------------------------
// Bind the socket to any address and the specified port.
RecvAddr.sin_family = AF_INET;
RecvAddr.sin_port = htons(Port);
RecvAddr.sin_addr.s_addr = htonl(INADDR_ANY);
bind(RecvSocket, (SOCKADDR *) &RecvAddr, sizeof(RecvAddr));
//-----------------------------------------------
// Call the recvfrom function to receive datagrams
// on the bound socket.
printf("Receiving datagrams...\n");
while(true){
recvfrom(RecvSocket,
RecvBuf,
BufLen,
0,
(SOCKADDR *)&SenderAddr,
&SenderAddrSize);
cout<<RecvBuf;
}
//-----------------------------------------------
// Close the socket when finished receiving datagrams
printf("Finished receiving. Closing socket.\n");
closesocket(RecvSocket);
//-----------------------------------------------
// Clean up and exit.
printf("Exiting.\n");
WSACleanup();
return;
}
Thank you very much for any help ..
Sorry for too much code in the question.
Per the docs, sendto returns a number that's >0 (number of bytes sent) for success, <0 for failure, and in the latter case you use WSAGetLastError for more information. So try saving the sendto result, printing it (as well as the size of the data you're trying to send), and in case of error print the last-error code too. What do you see then?
Related
I'm trying to test with OpenSSL DTLS by making a program that creates a client and server socket to echo strings between the sockets; However, when I try to test out DTLSv1_Listen() function my program seems to pause even when I am not trying connecting or sending data between the sockets. note: I am using a post 1.0.2 OpenSSL which is after DTLSv1_Listen() was rewritten.
Here is my complete C++ winsock specific code:
#include <stdio.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <openssl/err.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
//#include <openssl/applink.c>
#include <string>
#pragma comment(lib, "Ws2_32.lib")
struct DTLSStuff { //struct to contain DTLS object instances
SSL_CTX *ctx;
SSL *ssl;
BIO *bio;
};
void DTLSErr() { //DTLS error reporting
ERR_print_errors_fp(stderr);
exit(1);
}
int newSocket(sockaddr_in addr) { //creates a socket and returns the file descriptor //TODO expand for multi-platform
WSADATA wsaData;
int fd;
int iResult;
iResult = WSAStartup(MAKEWORD(2, 2), &wsaData); //Initialize Winsock
if (iResult != 0) { printf("WSAStartup failed: %d\n", iResult); exit(1); }
fd = socket(AF_INET, SOCK_DGRAM, 0); if (fd < 0) { perror("Unable to create socket"); exit(1); } //create socket
printf("New Socket: %i\n", fd);
if (bind(fd, (struct sockaddr *)&addr, sizeof(sockaddr)) < 0) { printf("bind failed with error %u\n", WSAGetLastError()); exit(1); }
return fd; //file descriptor
}
void InitCTX(SSL_CTX *ctx, bool IsClient) { //Takes a ctx object and initializes it for DTLS communication
if (IsClient) {
if(SSL_CTX_use_certificate_chain_file(ctx, "client-cert.pem") < 0) { printf("Failed loading client cert");}
if(SSL_CTX_use_PrivateKey_file(ctx, "client-key.pem", SSL_FILETYPE_PEM) < 0) { printf("Failed loading client key"); }
}
else {
if (SSL_CTX_use_certificate_chain_file(ctx, "server-cert.pem") < 0) { printf("Failed loading client cert"); }
if (SSL_CTX_use_PrivateKey_file(ctx, "server-key.pem", SSL_FILETYPE_PEM) < 0) { printf("Failed loading client key"); }
}
//SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, verify_cert); //omitted for testing
//SSL_CTX_set_cookie_generate_cb(ctx, generate_cookie); //omitted for testing
//SSL_CTX_set_cookie_verify_cb(ctx, verify_cookie); //omitted for testing
SSL_CTX_set_read_ahead(ctx, 1);
}
int main() { //creates client and server sockets and DTLS objects. TODO: have client complete handshake with server socket and send a message and have the server echo it back to client socket
BIO_ADDR *faux_addr = BIO_ADDR_new(); // for DTLSv1_listen(), since we are this is both client and server (meaning client address is known) it is only used to satisfy parameters.
ERR_load_BIO_strings();
SSL_load_error_strings();
SSL_library_init();
//Set up addresses
sockaddr_in client_addr;
client_addr.sin_family = AF_INET;
client_addr.sin_port = htons(25501);
client_addr.sin_addr.s_addr = INADDR_ANY;
sockaddr_in server_addr;
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(25500);
server_addr.sin_addr.s_addr = INADDR_ANY;
//*********CLIENT
DTLSStuff ClientInf;
ClientInf.ctx = SSL_CTX_new(DTLSv1_client_method());
InitCTX(ClientInf.ctx,true);
int ClientFD = newSocket(client_addr);
ClientInf.bio = BIO_new_dgram(ClientFD, BIO_NOCLOSE);
ClientInf.ssl = SSL_new(ClientInf.ctx);
//SSL_set_options(ClientInf.ssl, SSL_OP_COOKIE_EXCHANGE); //omitted for testing
SSL_set_bio(ClientInf.ssl, ClientInf.bio, ClientInf.bio);
//*********SERVER
DTLSStuff ServerInf;
ServerInf.ctx = SSL_CTX_new(DTLSv1_server_method());
InitCTX(ServerInf.ctx,false);
int ServerFD = newSocket(server_addr);
ServerInf.bio = BIO_new_dgram(ServerFD, BIO_NOCLOSE);
ServerInf.ssl = SSL_new(ServerInf.ctx);
//SSL_set_options(ServerInf.ssl, SSL_OP_COOKIE_EXCHANGE); //omitted for testing
SSL_set_bio(ServerInf.ssl, ServerInf.bio, ServerInf.bio);
printf("Listen attempt...\n");
int ret = DTLSv1_listen(ServerInf.ssl, faux_addr);
if (ret < 0) { DTLSErr(); }
printf("this print should occur, but it never does");
exit(1);
}
I expect the results to be as follow:
NewSocket: 356
NewSocket: 360
Listen attempt...
this print should occur but it never does
However when running the program it never prints the last line. The program seems to respond as I am able to cancel the executable by ctrl+c so I am assuming it has not crashed or froze, but aside from that I am at a loss. My understanding is that the method should return 0 if nothing happens, >1 if it heard a clienthello, and <0 if an error occurred.
Also, a somewhat related question: Since DTLSv1_Listen() requires a BIO_ADDR to store the incoming requests address does that mean that separate client and servers programs will both require 2 sockets if they want to be able to both send and listen? Normally UDP clients and servers only need a single socket, but I cannot seem to figure a design to retain this with OpenSSL's DTLS.
I thank you for your time.
I don't see anywhere in your code where you set the socket to be non-blocking. In the default blocking mode when you attempt to read from the socket your program will pause until data has arrived. If you don't want that then make sure your set the appropriate option (I'm not a Windows programmer, but ioctlsocket seems to do the job: https://msdn.microsoft.com/en-us/library/windows/desktop/ms738573(v=vs.85).aspx)
does that mean that separate client and servers programs will both require 2 sockets if they want to be able to both send and listen
When using DTLSv1_listen() you are using the socket in an unconnected state, so you may receive UDP packets from multiple clients. DTLS is connection based so once DTLSv1_listen() returns successfully you are supposed to create a "connected" socket to the client address. So you have one socket for listening for new connections, and one socket per client communicating with your server.
Hello everyone.
I'm trying to use Windows sockets to send and receive UDP packets (in C++).
It worked well until three days ago, when the program stopped behaving properly.
To summarize the situation:
When calling WSAPoll() on my socket, it always returns my socket updated with EVERY revents possible (corresponding to every events I gave the pollfd), even if there is no server launched.
When calling recvfrom() and no server is launched, it returns SOCKET_ERROR with error code 10054(*).
When calling recvfrom() and a server is launched, it works properly - blocks until it receives something.
The behavior is the same whether I try to connect to localhost or to a distant host.
(*) I investigated this error. In UDP, it means that there is an ICMP problem. ("On a UDP-datagram socket this error indicates a previous send operation resulted in an ICMP Port Unreachable message.").
I indeed call sendto() before recvfrom(), so the problem's not here.
I tried to put down my firewall to see if it changed anything, but it didn't. I also tried to put down every network flowing through my PC. In this state I managed to get the program to work for a few minutes, but when I enabled the networks it stopped working again. I tried to repeat the process but it would not work anymore.
I tried compiling with both visual studio (2015) and MinGW.
I tried on another computer too (under Windows 7, mine has Windows 8.1), to no avail.
Here is a simple test file which does not work on my computer.
#undef _WIN32_WINNT
#define _WIN32_WINNT 0x501
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdio.h>
#include <vector>
#include <iostream>
int main() {
int clientSock;
char buf[100];
int serverPort;
/* Initializing WSA */
WSADATA wsaData;
WSAStartup(MAKEWORD(2, 2), &wsaData);
/* I create my socket */
struct addrinfo specs;
struct addrinfo *addr = new addrinfo;
ZeroMemory(&specs, sizeof(specs));
specs.ai_family = AF_INET;
specs.ai_socktype = SOCK_DGRAM;
specs.ai_flags = 0;
getaddrinfo("127.0.0.1", "2324", &specs, &addr);
clientSock = socket(addr->ai_family, addr->ai_socktype, addr->ai_protocol);
/* I get the server's address */
struct sockaddr_in serverAddr;
serverAddr.sin_family = AF_INET;
serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
serverAddr.sin_port = htons(2324);
int len = sizeof(struct sockaddr);
/* I'll poll & recvfrom on my socket */
std::vector<pollfd> fds;
pollfd fd;
fd.fd = clientSock;
fd.events = POLLRDNORM;
fd.revents = -1;
fds.push_back(fd);
while(1) {
memset(buf,0,sizeof(buf));
printf("\nClient--->: ");
gets(buf);
/* It's UDP, so it doesn't matter if there is someone to receive the packet */
sendto(clientSock, buf, strlen(buf), 0, (sockaddr*)&serverAddr ,len);
memset(buf,0,sizeof(buf));
int ret;
/* Always returns "1" */
if ((ret = WSAPoll(fds.data(), 1, 0)) > 0) {
std::cout << ret;
/* Always returns "-1" */
std::cout << recvfrom(clientSock,buf,sizeof(buf),0, (sockaddr*)&serverAddr,&len) << std::endl;
printf("\n--->From the server: ");
printf("%s",buf);
}
}
closesocket(clientSock);
WSACleanup();
return 0;
}
Two questions:
Why does WSAPoll() always returns an updated socket, even if there wasn't any interaction with it ?
Why does recvfrom() return this error and how can I fix it ? I suppose it comes from my computer. I tried allowing ICMP through my firewall but it didn't change anything, maybe I did something wrong ?
Edit: I fixed my main program (not shown here because it is way too large) by just ignoring any "error 10054" I received. Now it works the same way it does on Unix.
Still, it is not really a solution (ignoring an error code... meh) and if anyone knows why I get the "ICMP Port Unreachable" error when calling sendto(), I'd be glad to hear about it.
In Windows, if host A use UDP socket and call sendto() to send something to host B, but B doesn't bind any port so that B doesn't receive the message, and then host A call recvfrom() to receive some message, recvfrom() will failed, and WSAGetLastError() will return 10054.
It's a bug of Windows. If UDP socket recv a ICMP(port unreachable) message after send a message, this error will be stored, and next time call recvfrom() will return this error.
There are 2 ways to solve this problem:
Make sure host B has already bound the port you want to send to.
Disable this error by using following code:
#include <Winsock2.h>
#include <Mstcpip.h>
#include <stdio.h>
#pragma comment(lib, "ws2_32.lib")
#define SIO_UDP_CONNRESET _WSAIOW(IOC_VENDOR, 12)
BOOL bNewBehavior = FALSE;
DWORD dwBytesReturned = 0;
WSAIoctl(iSock, SIO_UDP_CONNRESET, &bNewBehavior, sizeof bNewBehavior, NULL, 0, &dwBytesReturned, NULL, NULL);
Reference:
http://www.cnblogs.com/cnpirate/p/4059137.html
I have stripped down the Authors code and included the fix of simmerlee. This provides an simpler way to reproduce the error:
#include "stdafx.h"
#include <winsock2.h>
#include <stdio.h>
#pragma comment(lib, "ws2_32.lib")
#define SIO_UDP_CONNRESET _WSAIOW(IOC_VENDOR, 12)
void testCase(bool fixed)
{
int clientSock;
char rcvBuf[100];
// create socket
clientSock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if(fixed)
{
BOOL bNewBehavior = FALSE;
DWORD dwBytesReturned = 0;
WSAIoctl(clientSock, SIO_UDP_CONNRESET, &bNewBehavior, sizeof bNewBehavior, NULL, 0, &dwBytesReturned, NULL, NULL);
}
// bind socket
struct sockaddr_in clientAddr;
clientAddr.sin_family = AF_INET;
clientAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
clientAddr.sin_port = htons(61234);
int sizeClientAddr = sizeof(clientAddr);
bind(clientSock, (sockaddr*) &clientAddr, sizeClientAddr);
struct sockaddr_in serverAddr = clientAddr;
serverAddr.sin_port = htons(2324); // change port where nobody listens
int sizeServerAddr = sizeof(struct sockaddr);
int lasterror = 0;
int status = 0;
// send where nobody is listening
printf("Send to nowhere--->:\n");
/* It's UDP, so it doesn't matter if there is someone to receive the packet */
status =sendto(clientSock, "Message", 7, 0, (sockaddr*)&serverAddr, sizeServerAddr);
lasterror = WSAGetLastError();
printf("sendto return %d (lasterror %d)\n", status, lasterror);
// recvfrom with "failing" sendto before.
// fixed: This should block.
// unfixed: WSAGetLastError is 10054
memset(rcvBuf, 0, sizeof(rcvBuf));
status = recvfrom(clientSock, rcvBuf, sizeof(rcvBuf), 0, (sockaddr*)&serverAddr, &sizeServerAddr);
lasterror = WSAGetLastError();
printf("recvfrom return %d (lasterror %d)\n", status, lasterror);
printf("--->From the server: -%s-\n", rcvBuf);
closesocket(clientSock);
}
int _tmain(int argc, _TCHAR* argv[])
{
/* Initializing WSA */
WSADATA wsaData;
WSAStartup(MAKEWORD(2, 2), &wsaData);
printf("##### UNFIXED\n");
testCase(false);
printf("##### FIXED\n");
testCase(true);
WSACleanup();
// pause
char buf[100];
gets(buf);
return 0;
}
This should return:
##### UNFIXED
Send to nowhere--->:
sendto return 7 (lasterror 0)
recvfrom return -1 (lasterror 10054)
--->From the server: --
##### FIXED
Send to nowhere--->:
sendto return 7 (lasterror 0)
and then block.
I'm trying to create a UDP Server ,though without even client connecting to it, it recieves a connection...
(It writes in the console - New Connection a lot, so I guess it gets a new connection suddenly...)
#include <iostream>
#include <string>
#include <WinSock2.h>
#include <ws2tcpip.h>
#include <Windows.h>
#pragma comment(lib, "ws2_32.lib")
SOCKET ServerOn()
{
SOCKET ListenSocket;
WSADATA wsaData;
int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != NO_ERROR)
{
exit(0);
}
// Create a SOCKET for listening for
// incoming connection requests.
ListenSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (ListenSocket == INVALID_SOCKET)
{
WSACleanup();
exit(1);
}
// The sockaddr_in structure specifies the address family,
// IP address, and port for the socket that is being bound.
sockaddr_in service;
service.sin_family = AF_INET;
service.sin_addr.s_addr = inet_addr("0.0.0.0");
service.sin_port = htons(2583);
if (bind(ListenSocket,(SOCKADDR *) & service, sizeof (service)) == SOCKET_ERROR)
{
closesocket(ListenSocket);
WSACleanup();
exit(2);
}
return ListenSocket;
}
int main()
{
SOCKET ListenSocket = ServerOn();
SOCKET ClientSocket;
sockaddr_in service;
service.sin_family = AF_INET;
service.sin_addr.s_addr = inet_addr("10.0.0.2");
service.sin_port = htons(2583);
while(true)
{
if (ClientSocket = accept(ListenSocket, (SOCKADDR*)&service, NULL))
{
std::cout << "New Connection!" << std::endl;
}
}
}
Why is it getting connected without I ran anything? Maybe something else tries to connect to my server?
Thanks!
Two things: I don't think the IP address of your server can be 0.0.0.0, but instead 10.0.0.2; and also, UDP doesn't support the concept of 'accept'. There are just packets, and you can either bind a socket to a port, then receive packets from a specific IP (with recvfrom), or you can receive packets from anyone, with recv. The latter will be useful in case of a server. Note that you manually have to keep track of each connected client with a sockaddr_in structure.
I'll keep it simple.
Code:
#include "stdafx.h"
#include <winsock2.h>
#include <conio.h>
#include <iostream>
#include <stdio.h>
#include <tchar.h>
int _tmain(int argc, _TCHAR* argv[])
{
WSADATA wsadata;
int error = WSAStartup(0x0202, &wsadata);
if(error) printf("WinSock error!");
SOCKET server;
struct sockaddr_in server_addr;
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(5657);
server_addr.sin_addr.s_addr = htonl (INADDR_ANY);
server = socket(AF_INET, SOCK_STREAM, 0);
if (server == INVALID_SOCKET) printf("INVALID SOCKET!");
error = bind(server, (LPSOCKADDR)&server_addr, sizeof(server_addr));
if(error) printf("Connect Error!");
listen(server, SOMAXCONN);
printf("SERVER ESTABLISHED! LISTENING...\n");
sockaddr_in client_addr;
SOCKET client;
client = accept(server, (struct sockaddr*)&client_addr, (int *)sizeof(client_addr));
if(client==INVALID_SOCKET) printf("INVALID SOCKET!\n");
printf("A CLIENT!");
closesocket(server);
WSACleanup();
getch();
return 0;
}
But what I get is:
SERVER ESTABLISHED! LISTENING...
INVALID SOCKET!
A CLIENT!
I've done sockets in C# and I guess the server is supposed to listen and wait for a client, and whenever a client requests for a connection, the server should accept it, but the server accepts a socket without waiting, and this accepted socket is invalid, too! Why does this happen and how can I solve it?
This:
(int *)sizeof(client_addr)
is wrong, you're casting the size to a pointer.
socklen_t client_addr_len = sizeof(client_addr);
client = accept(server, (struct sockaddr*)&client_addr, &client_addr_len);
(int *)sizeof(client_addr)
You're casting the client_addr size into an int*, so you have a pointer that points to an address which is equal to the size of your client_addr.
You need to do:
socklen_t clntAddrLen = sizeof(client_addr);
client = accept(server, (struct sockaddr*)&client_addr, &clntAddrLen);
This way is different because you have a variable of type socklen_t which holds the size of your client_addr. You're then getting a pointer (with &) that points to the memory address where that number is contained which is what you want.
The problem may be that accept will attempt to write to the last argument provided to it.
Change to:
int client_addr_size = sizeof(client_addr);
client = accept(server, (struct sockaddr*)&client_addr, &client_addr_size);
Checking the value of WSAGetLastError will provide the reason for failure.
I am trying to make a program using Winsock2 where I can send a message from client to server. I can do this, but the problem is I can only send one message and then I have to restart the server to receive the next message. Here is the code for the server. The part I am really confused about is I have the recv() function in a while loop so why isn't it continuing to "receive" data?
WSADATA wsaData;
int bytes_recieved;
char data_recieve[2048];
string output;
WSAStartup(MAKEWORD(2, 2), &wsaData);
SOCKET ListenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
SOCKADDR_IN ServerInfo;
ServerInfo.sin_family = AF_INET;
ServerInfo.sin_addr.s_addr = INADDR_ANY;
ServerInfo.sin_port = htons(8888);
bind(ListenSocket, (LPSOCKADDR)&ServerInfo, sizeof(struct sockaddr));
listen(ListenSocket, 1);
SOCKET ClientSocket = accept (ListenSocket, NULL, NULL);
while(true)
{
bytes_recieved = recv(ClientSocket, data_recieve, 2048, 0);
if (bytes_recieved > 1)
{
cout << data_recieve;
}
}
closesocket(ClientSocket);
closesocket(ListenSocket);
WSACleanup();
The client (sender) is listed below.
WSADATA wsaData;
int bytes_sent;
char send_msg[] = "super cool message!";
WSAStartup(MAKEWORD(2, 2), &wsaData);
SOCKET ConnectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
sockaddr_in ConnectInfo;
ConnectInfo.sin_family = AF_INET;
ConnectInfo.sin_addr.s_addr = inet_addr("127.0.0.1");
ConnectInfo.sin_port = htons(8888);
connect(ConnectSocket, (SOCKADDR*)&ConnectInfo, sizeof(ConnectInfo));
bytes_sent = send(ConnectSocket, send_msg, sizeof(send_msg), 0);
closesocket(ConnectSocket);
WSACleanup();
I am doing this in Windows 7 with a MinGW compiler. Thank you in advance.
You did not show your client sending code, but offhand, your server reading code is not taking into account that sends and receives are NOT 1-to-1 in TCP/IP programming. If a client sends 2 messages, the server may receive both messages, or even portions of them, in the same read operation! You ae telling your server socket to read 2048 bytes at a time. It will return whatever is currently available on the socket at that moment. TCP/IP is a byte stream, you need to treat it as much. That means you need to either put a delimiter in between your messages, or put a frame around them, in order to know where one message ends and the next message begins.