Hi,
I want the code for Client and Server Socket to send a text message from one computer to another. I used the help file, but it dosen't provide enough information. I am doing this program in C++ Builder.
Thanks
Hi,
I want the code for Client and Server Socket to send a text message from one computer to another. I used the help file, but it dosen't provide enough information. I am doing this program in C++ Builder.
Thanks
Here's a minimal example
/* CLIENT */
#include <winsock.h>
#include <stdio.h>
int main( int argc, char** argv){
char pBuf[2048];
WSADATA wsaData;
SOCKET sClient;
int connected;
SOCKADDR_IN RemoteAddr; RemoteAddr.sin_family=PF_INET;
RemoteAddr.sin_addr.s_addr=inet_addr("127.0.0.1");
RemoteAddr.sin_port=htons(5555);
WSAStartup(MAKEWORD(1, 1), &wsaData);
sClient=socket(AF_INET, SOCK_STREAM, 0);
connected = 1;
while(connected){
connected = connect(sClient, (PSOCKADDR)&RemoteAddr, sizeof(SOCKADDR));
if(!connected){
strcpy(pBuf,"");
while(strcmp(pBuf,"end")){
scanf("%s",&pBuf);
send(sClient, pBuf, strlen(pBuf)+1, 0);}}}
closesocket(sClient);
WSACleanup();
return 0;}
/* SERVER */
#include <winsock.h>
#include <stdio.h>
int main(int argc, char** argv) {
char pBuf[2048];
WSADATA wsaData; WORD version;
SOCKET listeningSocket, theClient;
SOCKADDR_IN saServer; saServer.sin_family = AF_INET;
saServer.sin_addr.s_addr = INADDR_ANY;
saServer.sin_port = htons(5555);
version = MAKEWORD(1,1);
WSAStartup(version, &wsaData);
listeningSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
bind(listeningSocket, (LPSOCKADDR)&saServer, sizeof(struct sockaddr));
listen(listeningSocket, 10);
theClient=INVALID_SOCKET;
while(1){
theClient = accept(listeningSocket,NULL, NULL);
if(theClient!=INVALID_SOCKET)
while(strcmp(pBuf,"end")){
recv(theClient, pBuf, 2048, 0);
printf( "-->%s\n", pBuf);}
strcpy(pBuf,"");
theClient=INVALID_SOCKET;}
closesocket(theClient);
closesocket(listeningSocket);
WSACleanup();
return 0;}
Thaks for your code, it actually works, but I have a question? Where do you put the code?
Thanks
What is your purpose ?
Is it a windowed app?
It's a school project that I have to send a message from one computer to another using the same program like a chat line.
THank you