Sending message from C# client to C server -
i'm new socket programming, but, using online tutorial, i've sent short string 1 machine using c.
the problem i'm having trying send string client written in c#. server (written in c) prints out blank/empty string.
here c code runs on "server" machine (in case router running openwrt):
int main(int argc, char *argv[]) { int listenfd = 0, connfd = 0; struct sockaddr_in serv_addr; char recvbuff[1025]; int bytesread; listenfd = socket(af_inet, sock_stream, 0); memset(&serv_addr, '0', sizeof(serv_addr)); serv_addr.sin_family = af_inet; serv_addr.sin_addr.s_addr = htonl(inaddr_any); serv_addr.sin_port = htons(1234); bind(listenfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr)); printf("listening string on port 1234...\n"); listen(listenfd, 10); while(1) { connfd = accept(listenfd, (struct sockaddr*)null, null); bytesread = recv(connfd, recvbuff, 1024, 0); // receive string if (bytesread < 0) { printf("error reading stream\n"); } recvbuff[bytesread] = 0; // null-terminate string printf("%d:%s\n", bytesread, recvbuff); close(connfd); sleep(1); } }
when sending little server string c program works expected (prints string out waits one). [note: don't think c client's code relevant, can post if need be]
however, when trying send string c# program (copied below), server prints out 0:
(i.e. 0 bytes read, followed empty string) , can't life of me figure out issue is. both apps pretty straightforward, i'm assuming should using other writeline
(i've tried write
no avail).
c# client:
namespace sockettest { class program { static void main(string[] args) { tcpclient client = new tcpclient("10.45.13.220", 1234); stream stream = client.getstream(); streamwriter writer = new streamwriter(stream); writer.writeline("testing..."); client.close(); } } }
to null terminate string use
recvbuff[bytesread] = '\0';
and call close on writer (which causes writer flush pending bytes)
writer.writeline("testing..."); writer.close(); client.close();
Comments
Post a Comment