How to make a full-duplex c++ winsock chat program - c++

I'm trying to make a simple client-server chat program in C++. I wrote this, but my problem is that I can just send data from the server to the client. I want to have a full-duplex communication, and send data from client to server too.
Here is my code.
server :
#include "stdafx.h"
#include <WinSock2.h>
#include <winsock.h>
#include <stdio.h>
#include <iostream>
#include <string>
#define RCVBUFSIZE 32
using namespace std;
#pragma comment(lib, "Ws2_32.lib")
int main()
{
WSADATA wsadat;
SOCKET welcome_socket = INVALID_SOCKET;
string IpAddress;
int PortNom;
SOCKADDR_IN SockAddress;
//-----------------------------------------------
if (WSAStartup(MAKEWORD(2,2),&wsadat) !=NO_ERROR)
{
cout << "WSA intialization failed. \n";
WSACleanup();
return 1;
}
//------------------------------------------------
welcome_socket = socket(AF_INET , SOCK_STREAM , 0);
//--------------------------------------------------
cout << "Enter your ip address: ";
cin >> IpAddress;
cout << "Enter your port nomber:";
cin >> PortNom;
//---------------------------------------------------
SockAddress.sin_addr.s_addr = inet_addr (IpAddress.c_str());
SockAddress.sin_port = htons(PortNom);
SockAddress.sin_family = AF_INET;
//---------------------------------------------------
bind(welcome_socket,(SOCKADDR *)&SockAddress,sizeof(SockAddress));
listen(welcome_socket,1);
//----------------------------------------------------
SOCKET Comm_sock;
SOCKADDR_IN ClientAddr;
int AddressLen = sizeof (ClientAddr);
char *buffer = new char[13];
int turn= 0;
char* buf = new char[50];
char temp;
while (true)
{
Comm_sock = accept(welcome_socket,(SOCKADDR *)&ClientAddr , &AddressLen);
while (buf != "exit")
{
if (turn == 0)
{
cout << endl;
recv(Comm_sock,buf,50,0);
if(buf[0]=='e' && buf[1]=='x' && buf[2]=='i' && buf[3]=='t')
return 0;
cout << "MsG from client :"<< buf << endl;
cin.get(temp);
turn = 1;
}
if (turn == 1)
{
cout << "Enter MsG:";
cin.get(buf,50);
if (buf[0]=='e' && buf[1]=='x' && buf[2]=='i' && buf[3]=='t')
return 0;
send(Comm_sock,buf,strlen(buf)+1,0);
cin.get(temp);
turn=0;
}
}
}
and client:
#include "stdafx.h"
#include <winsock2.h>
#include <Ws2tcpip.h>
#include <stdio.h>
#include <iostream>
using namespace std;
// Link with ws2_32.lib
#pragma comment(lib, "Ws2_32.lib")
#define DEFAULT_BUFLEN 512
#define DEFAULT_PORT "12345"
//-------------------------------------
int main ()
{
WSADATA wsadata;
int iResult;
SOCKET ConnectSocket = INVALID_SOCKET;
struct sockaddr_in clientservice;
char *sendbuf ="";
char recvbuf[DEFAULT_BUFLEN];
char sendbuffer[512];
int recvbuflen = DEFAULT_BUFLEN;
int sendbuflen = 512;
//----------------------------------
iResult = WSAStartup(MAKEWORD(2,2),&wsadata);
//----------------------------------
ConnectSocket = socket(AF_INET,SOCK_STREAM , IPPROTO_TCP);
//-----------------------------------
clientservice.sin_family = AF_INET;
clientservice.sin_addr.s_addr = inet_addr( "127.0.0.1" );
clientservice.sin_port = htons( 11111 );
//-----------------------------------
iResult = connect (ConnectSocket,(SOCKADDR *)&clientservice ,sizeof(clientservice));
iResult = send( ConnectSocket, sendbuf, (int)strlen(sendbuf), 0 );
cout << "bytes Sent:" << iResult << "\n";
//-------------------------------------
iResult = shutdown(ConnectSocket ,SD_SEND);
if (iResult == SOCKET_ERROR)
{
printf("shutdown failed: %d\n", WSAGetLastError());
closesocket(ConnectSocket);
WSACleanup();
return 1;
}
do {
string reciev;
iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0);
recvbuf[iResult]= 0 ;
cout << recvbuf << endl;
} while(true);
//------------------------------------------
closesocket(ConnectSocket);
WSACleanup();
}

Related

UDP client can not recieve data from server in C++

I am new for C++. I tried to write a UDP client and server in C++. The server can receive data from client. But the client can not receive data from server. No matter what data the server sends, the method recvfrom in client always returns 0.
The client code is below:
#include <winsock2.h>
#include <stdio.h>
#include <string.h>
#include <iostream>
using namespace std;
#pragma comment(lib, "ws2_32.lib")
#define BUFFER_SIZE 1024
int main()
{
SOCKET sock_Client;
WSADATA WSAData;
char receBuf[BUFFER_SIZE];
char sendBuf[BUFFER_SIZE];
if (WSAStartup(MAKEWORD(2, 2), &WSAData) != 0)
{
printf("initialation fails!");
return -1;
}
sock_Client = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
SOCKADDR_IN addr_server;
addr_server.sin_family = AF_INET;
addr_server.sin_port = htons(4567);
addr_server.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
SOCKADDR_IN sock;
int len = sizeof(sock);
while (true)
{
cout << "input data to send:";
cin >> sendBuf;
sendto(sock_Client, sendBuf, strlen(sendBuf), 0, (SOCKADDR*)&addr_server, sizeof(SOCKADDR));
//int last=recv(sock_Client, receBuf, strlen(receBuf), 0); //
int last = recvfrom(sock_Client, receBuf, strlen(receBuf), 0, (SOCKADDR*)&sock, &len);
if (last > 0)
{
receBuf[last] = '\0';
if (strcmp(receBuf, "bye") == 0)
{
cout << "server stops talking..." << endl;
closesocket(sock_Client);
break;
}
else
{
printf("received data:%s\n", receBuf);
}
}
}
closesocket(sock_Client);
WSACleanup();
return 0;
}
The server code:
#include <winsock2.h>
#include <stdio.h>
#include <string.h>
#include <iostream>
using namespace std;
#pragma comment(lib, "ws2_32.lib")
#define BUFFER_SIZE 1024
int main()
{
WSADATA WSAData;
char receBuf[BUFFER_SIZE];
char Response[BUFFER_SIZE];
if (WSAStartup(MAKEWORD(2, 2), &WSAData) != 0)
{
printf("initialation fails!");
exit(1);
}
SOCKET sockServer = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (sockServer == INVALID_SOCKET)
{
printf("Failed socket() \n");
return 0;
}
SOCKADDR_IN addr_Server;
addr_Server.sin_family = AF_INET;
addr_Server.sin_port = htons(4567);
addr_Server.sin_addr.S_un.S_addr = INADDR_ANY;
if (bind(sockServer, (SOCKADDR*)&addr_Server, sizeof(addr_Server)) == SOCKET_ERROR)
{
printf("Failed socket() %d \n", WSAGetLastError());
return 0;
}
SOCKADDR_IN addr_Clt;
int fromlen = sizeof(SOCKADDR);
while (true)
{
int last = recvfrom(sockServer, receBuf, 1024, 0, (SOCKADDR*)&addr_Clt, &fromlen);
if (last > 0)
{
receBuf[last] = '\0';
if (strcmp(receBuf, "bye") == 0)
{
cout << " client stop talking..." << endl;
closesocket(sockServer);
return 0;
}
else
{
printf("received data(%s):%s\n", inet_ntoa(addr_Clt.sin_addr), receBuf);
}
}
cout << "anser client:";//<br>Response = “”;
cin >> Response;
sendto(sockServer, Response, strlen(Response), 0, (SOCKADDR*)&addr_Clt, sizeof(SOCKADDR));
}
closesocket(sockServer);
WSACleanup();
return 0;
}
Anyone know what is wrong with the code?
The code runs in Windows. So, set(CMAKE_CXX_STANDARD 14) has to be added into CMakeLists.txt. If you want to run the code, please notice that.

cannot send nor receive data through sockets

I tried making a simple server-client socket communication but something seems to no work properly with the server. I get this error whenever I send or receive:
Socket operation on non-socket: Socket operation on non-socket
Strangely enough, this only appears whenever the server is sending.
the client seems to be ok:
//server
#include <iostream>
#include <sys/socket.h>
#include <string.h>
#include <netinet/in.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <arpa/inet.h>
using namespace std;
int main(){
const int PORT = 5000;
int serverfd, clientfd, opt=1, n_send, n_recv;
sockaddr_in server_address, client_address;
char recvbuf[1024], sendbuf[1024];
bzero(&server_address , sizeof(server_address));
inet_pton(AF_INET, "127.0.0.1",&server_address.sin_addr);
int x = INADDR_ANY;
server_address.sin_family = AF_INET;
server_address.sin_port = htons(PORT);
socklen_t addrSize = sizeof(server_address);
if((serverfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0){
perror(strerror(errno));
exit(EXIT_FAILURE);
}
if((setsockopt(serverfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt))) < 0){
perror(strerror(errno));
exit(EXIT_FAILURE);
}
if((bind(serverfd, (sockaddr*)&server_address, sizeof(server_address)))< 0){
perror(strerror(errno));
exit(EXIT_FAILURE);
}
if((listen(serverfd, 1))< 0){
perror(strerror(errno));
exit(EXIT_FAILURE);
}
if((clientfd = accept(serverfd, (sockaddr *)&server_address, (socklen_t*)&addrSize) < 0)){
perror(strerror(errno));
exit(EXIT_FAILURE);
}
while (true){
cout << "SAY TO CLIENT: ";
bzero(sendbuf, sizeof(sendbuf));
cin >> sendbuf;
cout << endl;
send(clientfd, sendbuf, strlen(sendbuf), 0);
errno = 0;
bzero(recvbuf, sizeof(recvbuf));
if((n_recv = recv(clientfd, recvbuf, sizeof(recvbuf), MSG_WAITALL))< 0){
perror(strerror(errno));
exit(EXIT_FAILURE);
}
cout << recvbuf << endl;
}
return 0;
}
//client
#include <iostream>
#include <sys/socket.h>
#include <string.h>
#include <netinet/in.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <arpa/inet.h>
using namespace std;
int main(){
const int PORT = 5000;
int sockfd, n_send, n_recv;
char recvbuf[1024], sendbuf[1024];
sockaddr_in server_address;
bzero(&server_address, sizeof(server_address));
server_address.sin_family= AF_INET;
server_address.sin_port = htons(PORT);
inet_pton(AF_INET, "127.0.0.1", &server_address.sin_addr);
if((sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0){
perror(strerror(errno));
exit(EXIT_FAILURE);
}
if(connect(sockfd, (sockaddr *) &server_address, sizeof(server_address))<0){
perror(strerror(errno));
exit(EXIT_FAILURE);
}
while (true){
if((n_recv = recv(sockfd, recvbuf, sizeof(recvbuf), MSG_WAITALL)) < 0){
perror(strerror(errno));
exit(EXIT_FAILURE);
}
cout << "Server: " << recvbuf << endl;
cout << "Say to server: ";
cin >> sendbuf;
cout << endl;
if((n_send = send(sockfd, sendbuf, sizeof(sendbuf), 0)) < 0){
perror(strerror(errno));
exit(EXIT_FAILURE);
}
}
return 0;
}
clientfd is assigned a non-socket value. If we change the whitespace in your if:
if((clientfd =
accept(serverfd, (sockaddr *)&server_address, (socklen_t*)&addrSize) < 0
)) {
perror(strerror(errno));
exit(EXIT_FAILURE);
}
Because of the way you wrote it, the result of accept (the presumably valid socket) is checked, and that result is set to clientFd. Note that your parenthesis placement doesn't match your other lines.

c++ socket timeout error when trying to connect

I've recently into c/c++ socket programming so I just made simple program that server and client respond each other. My server is in VMware( linux fedora) and client is windows(in visual studio 2017).
And it worked(pls notice that server and client are in one laptop)..
I also tried same client code with another computer(my deskTop) and got a WSAETIMEDOUT(10060)
error. The error was captured in connect() function in client code.
I have no idea how to solve :(
Could anybody help me?
Here's a client code
#include <iostream>
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#include <WinSock2.h>
using namespace std;
#define DEFAULT_BUFLEN 512
int main(int argc, char *argv[]) {
WSADATA wsaData;
SOCKET connectSocket;
SOCKADDR_IN servAddr;
char sendBuf[DEFAULT_BUFLEN];
char recvBuf[DEFAULT_BUFLEN];
char nickName[DEFAULT_BUFLEN];
int recvLen = 0;
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
cout << "start up error";
exit(1);
}
connectSocket = socket(PF_INET, SOCK_STREAM, 0);
if (connectSocket == INVALID_SOCKET) {
cout << "socket creation error";
exit(1);
}
memset(&servAddr, 0, sizeof(servAddr));
servAddr.sin_family = AF_INET;
servAddr.sin_addr.s_addr = inet_addr(argv[1]);
servAddr.sin_port = htons(atoi(argv[2]));
if (connect(connectSocket, (SOCKADDR*)&servAddr, sizeof(servAddr)) == SOCKET_ERROR) {
cout << "connect error: " << WSAGetLastError();
exit(1);
}
while (1) {
recvLen = recv(connectSocket, recvBuf, sizeof(recvBuf), 0);
if (recvLen > 0) {
if (strcmp(recvBuf, "Exit") == 0)
break;
cout << recvBuf;
//cin >> nickName;
cin.getline(nickName, DEFAULT_BUFLEN);
send(connectSocket, nickName, sizeof(nickName),0);
}
else if (recvLen == 0)
cout << "Connection closed";
else if (recvLen == -1)
cout << "Connection failed";
}
closesocket(connectSocket);
WSACleanup();
return 0;
}
Blockquote
and server code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <iostream>
#include <string>
#define DEFAULT_LEN 512
#define DEFAULT_CLIENT_NUM 30
using namespace std;
char nickNameCommand[]="Please set your nickName:";
void error_handling(char * message);
class Client {
private:
char nickName[DEFAULT_LEN];
int clientSock;
public:
struct sockaddr_in clnt_addr;
int& getClientSock(){
return clientSock;
}
};
class Server {
private:
int serv_sock;
char informClientNickName[DEFAULT_LEN] = "Your NickName is ";
public:
Server(){
}
char message[DEFAULT_LEN]= "";
char clientNickName[DEFAULT_CLIENT_NUM][DEFAULT_LEN];
struct sockaddr_in serv_addr;
void setServSock(int value){
serv_sock = value;
}
int getServSock(){
return serv_sock;
}
void setInformClientNickName(int clientNum){
strcat(informClientNickName,clientNickName[clientNum]);
strcat(message , informClientNickName);
}
char* getInformClientNickName(){
return informClientNickName;
}
};
int main(int argc,char * argv[])
{
Client clientSocket[DEFAULT_CLIENT_NUM];
Server server;
int clientNum=0;
int recvLen=0;
socklen_t clnt_addr_size;
char message[DEFAULT_LEN];
if(argc!=2)
{
printf("Usage: %s <port>\n",argv[0]);
exit(1);
}
server.setServSock(socket(PF_INET,SOCK_STREAM,0));
if(server.getServSock() == -1)
error_handling("socket() error");
memset(&(server.serv_addr),0,sizeof(server.serv_addr));
server.serv_addr.sin_family=AF_INET;
server.serv_addr.sin_addr.s_addr=htonl(INADDR_ANY);
server.serv_addr.sin_port=htons(atoi(argv[1]));
if(bind(server.getServSock(),(struct sockaddr*)&
(server.serv_addr),sizeof(server.serv_addr)) ==-1)
error_handling("bind() error");
if(listen(server.getServSock(),5)==-1)
error_handling("listen() error");
clnt_addr_size=sizeof(clientSocket[0].clnt_addr);
while(1) {
clientSocket[clientNum].getClientSock() = accept(server.getServSock(),
(struct sockaddr*)&(clientSocket[clientNum].clnt_addr),&clnt_addr_size);
if(clientSocket[clientNum].getClientSock()==-1)
error_handling("accept() error");
else{
write(clientSocket[clientNum].getClientSock(),nickNameCommand,sizeof(nickNameCommand));
read(clientSocket[clientNum].getClientSock(),(void*)(server.clientNickName[clientNum]),DEFAULT_LEN);
}
cout << "Received name is : " << server.clientNickName[clientNum]<<endl;
clientNum++;
cout << "ClientNum: " << clientNum <<endl;
recvLen=0;
for(int i=0;i<clientNum;i++){
server.setInformClientNickName(i);
write(clientSocket[clientNum].getClientSock(),server.message,sizeof(server.message));
}
}
for(int i=0;i<clientNum;i++)
close(clientSocket[i].getClientSock());
close(server.getServSock());
return 0;
}
void error_handling(char * message)
{
fputs(message,stderr);
fputc('\n',stderr);
exit(1);
}

Multiple clients in c++ server

Yesterday I started writing a code for server-client TCP/IP for chating.
It's code for server:
#include <iostream>
#include <winsock2.h>
#pragma comment(lib, "Ws2_32.lib")
int main() {
WSAData wsa;
WORD Version = MAKEWORD(2, 1);
WSAStartup(Version, &wsa);
SOCKET Listen = socket(AF_INET, SOCK_STREAM, 0);
SOCKET Connect = socket(AF_INET, SOCK_STREAM, 0);
SOCKADDR_IN Server;
Server.sin_addr.s_addr = inet_addr("127.0.0.1");
Server.sin_family = AF_INET;
Server.sin_port = htons(100);
bind(Listen, (SOCKADDR*)&Server, sizeof(Server));
listen(Listen, 1);
int size = sizeof(Server);
char buffer[512];
char *fn = "";
int iResult;
std::cout <<"Listening...";
if(Connect = accept(Listen, (SOCKADDR*)&Server, &size)) {
std::cout << "\nConnecting was reached :)";
}
do {
char *fn;
iResult = recv(Connect, buffer, sizeof(buffer), 0);
if (iResult > 0) {
buffer[iResult] = '\0';
fn = buffer;
std::cout << fn;
} else if (iResult == 0){
printf("Connection closing...\n");
iResult = 0;
}
} while (iResult > 0);
WSACleanup();
std::cin.get();
return 0;
}
And it's for client:
#include <iostream>
#include <winsock2.h>
#include <string>
#pragma comment(lib, "Ws2_32.lib")
int main() {
WSAData wsa;
WORD Version = MAKEWORD(2, 1);
WSAStartup(Version, &wsa);
int iResult;
std::string text;
char buffer[512];
SOCKADDR_IN Client;
Client.sin_addr.s_addr = inet_addr("127.0.0.1");
Client.sin_family = AF_INET;
Client.sin_port = htons(100);
SOCKET Connect = socket(AF_INET, SOCK_STREAM, 0);
std::cout << "Wcisnij enter aby polaczyc";
std::cin.get();
if(connect(Connect, (SOCKADDR*)&Client, sizeof(Client))) {
std::cout << "Nawiazano polaczeniee";
}
do {
std::cout << "Waxer: ";
std::cin >> text;
text.insert( 0, "Waxer: " );
strcpy_s(buffer, text.c_str());
// Send an initial buffer
iResult = send(Connect, buffer, strlen(buffer), 0);
if (iResult == SOCKET_ERROR) {
printf("send failed with error: %d\n", WSAGetLastError());
closesocket(Connect);
WSACleanup();
return 1;
}
} while(text != "ban");
std::cout<< "Polaczenie wyslane!";
std::cin.get();
return 0;
}
My question is? What should I change in this code for multiple clients. I mean how to connect new clients?
Your question is quite open, but in general you need threads.
Pseudocode:
int main()
{
std::vector<std::thread> clients;
Socket listener("localhost", "1337");
for (;;)
{
Socket tmp = listener.accept();
clients.push_back(std::thread(&myHandlerFunction, tmp));
clients.back().detach();
}
}
In the end you have a thread for every connected client and can codify your chat logic so that they can communicate with each other.

UDP respond on connected socket

So I've been programming with TCP for quite a while, and decided to pick up UDP. I'm not quite sure what needs to be done in order for me to have communication both ways across the WAN(or lan for that matter, easier on lan because I could just open two ports) With UDP once I send information from client to server how can I respond on that socket. Is there a way to connect directly?
(Current quick functions)
int udpsock(int port, const char* addr){
int handle = socket( AF_INET, SOCK_DGRAM, IPPROTO_UDP );
if (handle < 1)
return -1;
sockaddr_in address;
address.sin_family = AF_INET;
if (addr == INADDR_ANY)
address.sin_addr.s_addr = INADDR_ANY;
else
address.sin_addr.s_addr = inet_addr(addr);
address.sin_port = htons( (unsigned short) port );
if ( bind( handle, (const sockaddr*) &address, sizeof(sockaddr_in) ) < 0 )
return -1;
return handle;
}
string recvudp(int sock,const int size){
sockaddr_in SenderAddr;
int SenderAddrSize = sizeof (SenderAddr);
char buf[size];
int retsize = recvfrom(sock, buf, sizeof(buf), 0, (SOCKADDR *) & SenderAddr, &Sen derAddrSize);
if (retsize == -1){
cout << "\nRecv Error : " << WSAGetLastError();
if (WSAGetLastError() == WSAEWOULDBLOCK || WSAGetLastError() == 0){
return "";
}
return "\0";
}
else if (retsize < size){
buf[retsize] = NULL;
}
return buf;
}
int sendudp(string str, string ip, unsigned short port, int sock){
sockaddr_in dest;
dest.sin_family = AF_INET;
dest.sin_addr.s_addr = inet_addr( ip.c_str() );
dest.sin_port = htons( port );
int ret = sendto(sock,str.c_str(),str.size(),0, (sockaddr*)&dest,sizeof(dest));
if (ret == -1){
cout << "\nSend Error Code : " << WSAGetLastError();
}
return ret;
}
With this it's pretty easy to make a socket with port xxxx and have the partner send on that port to get data to the client, the forth part is where I'm having some trouble =]
Make your sendudp function take a sockaddr_in. You get one back from recvfrom and can pass it to sendto. Alternatively, pass the received sockaddr_in to connect and use send from then on.
I assume that functions you posted should be shared between client and server. They need to be slightly modified in order to achieve that. E.g. on the server side, recvudp should return client address (possibly as an out parameter) as it is needed later for sending message back to it. Furthermore, as client address structure is already filled (in recvudp on the server side or manually on the client side) we can just pass it to sendudp as its argument.
I've played with this a bit and created two simple projects in Visual Studio 2010: UDP Server and client. They both use shared functions mentioned above. This code is far from perfect and is aimed only to show basic UDP socket communication.
Shared.h:
#ifndef SHARED_H
#define SHARED_H
#include <winsock2.h>
#include <string>
int udpsock(int port, const char* addr);
std::string recvudp(int sock, const int size, sockaddr_in& SenderAddr, int& SenderAddrSize);
int sendudp(std::string str, sockaddr_in dest, int sock);
#endif
Shared.cpp:
#include "Include\shared.h" // path to header - you might use different one
#include <iostream>
using namespace std;
int udpsock(int port, const char* addr)
{
int handle = socket( AF_INET, SOCK_DGRAM, IPPROTO_UDP );
if (handle < 1)
return -1;
sockaddr_in address;
address.sin_family = AF_INET;
if (addr == INADDR_ANY)
address.sin_addr.s_addr = INADDR_ANY;
else
address.sin_addr.s_addr = inet_addr(addr);
address.sin_port = htons( (unsigned short) port );
if ( bind( handle, (const sockaddr*) &address, sizeof(sockaddr_in) ) < 0 )
return -1;
return handle;
}
// function should return sender address info (for the code the server)
string recvudp(int sock, const int size, sockaddr_in& SenderAddr, int& SenderAddrSize)
{
// TODO: use std::vector<char> here instead of char array
char* buf = 0;
buf = new char[size];
int retsize = recvfrom(sock, buf, size, 0, (sockaddr*) &SenderAddr, &SenderAddrSize);
if(retsize == -1)
{
cout << "\nRecv Error : " << WSAGetLastError();
if (WSAGetLastError() == WSAEWOULDBLOCK || WSAGetLastError() == 0)
{
return "";
}
return "\0";
}
else if (retsize < size)
{
buf[retsize] = NULL;
}
string str(buf);
delete[] buf;
return str;
}
// On the client side, prepare dest like this:
// sockaddr_in dest;
// dest.sin_family = AF_INET;
// dest.sin_addr.s_addr = inet_addr(ip.c_str());
// dest.sin_port = htons(port);
int sendudp(string str, sockaddr_in dest, int sock)
{
int ret = sendto(sock,str.c_str(),str.size(),0, (sockaddr*)&dest,sizeof(dest));
if (ret == -1)
{
cout << "\nSend Error Code : " << WSAGetLastError();
}
return ret;
}
Server: main.cpp:
#include <winsock2.h>
#include <string.h>
#include <iostream>
#include "..\Shared\Include\shared.h"
// Link with ws2_32.lib
#pragma comment(lib, "Ws2_32.lib")
#define SERVER_PORT 27015
#define MAX_MSG 1024
using namespace std;
int main(int argc, char *argv[])
{
WSADATA wsaData;
int nResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if(nResult != NO_ERROR)
{
cout << "WSAStartup failed with error: " << nResult << endl;
return 1;
}
sock = udpsock(SERVER_PORT, "127.0.0.1");
cout << "Waiting for datagram on port: " << SERVER_PORT << endl;
while(1)
{
sockaddr_in clientAddr;
// receive message
int clientAddrLen = sizeof(clientAddr);
cout << "Received message from the client: " << recvudp(sock, MAX_MSG, clientAddr, clientAddrLen) << endl;
sendudp("Hello from server!", clientAddr, sock);
}
WSACleanup();
return 0;
}
Client: main.cpp:
#include <winsock2.h>
#include <iostream>
#include "..\Shared\Include\shared.h"
using namespace std;
#define MAX_MSG 1024
// Link with ws2_32.lib
#pragma comment(lib, "Ws2_32.lib")
int main(int argc, char* argv[])
{
WSADATA wsaData;
int nResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (nResult != NO_ERROR)
{
cout << "WSAStartup failed with error: " << nResult << endl;
return 1;
}
SOCKET sock = INVALID_SOCKET;
// Create a socket for sending data - it does not need to be binded like listening socket!
sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if(sock == INVALID_SOCKET)
{
cout << socket failed with error: " << WSAGetLastError() << endl;
WSACleanup();
return 1;
}
unsigned short Port = 27015;
sockaddr_in dest;
dest.sin_family = AF_INET;
dest.sin_addr.s_addr = inet_addr("127.0.0.1");
dest.sin_port = htons(Port);
sendudp("Hello from client!", dest, sock);
sockaddr_in RecvAddr;
int recvaddrlen = sizeof(RecvAddr);
cout << "Received message from the server: " << recvudp(sock, MAX_MSG, RecvAddr, recvaddrlen) << endl;
cout << "Closing socket..." << endl;
nResult = closesocket(sock);
if(nResult == SOCKET_ERROR)
{
cout << "closesocket failed with error: " << WSAGetLastError() << endl;
WSACleanup();
return 1;
}
WSACleanup();
return 0;
}
If you run client twice output is:
Server:
Waiting for datagram on port: 27015
Received message from the client: Hello from client!
Received message from the client: Hello from client!
Client:
Received message from the server: Hello from server!
Closing socket...
UDP is connectionless protocol, server just needs to start listening on UDP port and client can send data (datagram) immediately, there is no need for connection establishment (e.g. with connect()/accept(), like in TCP).