I'm using socket API to make a simple chat program using UDP socket (SO_BROADCAST)
To make it simple, at first, I created 1 socket named "socketa" in Application "AppA" to send message and created another socket "socketb" in Application "AppB" to receive message from "AppA". It worked perfectly, but only one-way.
So, I want it to work in two-way communication, i.e. both send and receive message. I wonder whether I should create more sockets, e.g. "socketa2" in Application "AppA" to receive message and "socketb2" in Application "AppB" to send message?
So, please tell me that can a socket both Send and Receive message? And how to design this two-way communication?
I'm new to c++ and also windows socket, so I really appreciate someone giving me a detailed example how to do this.
you need to know the address and port of the target... you get those information from the sockaddr structure you get back fullfilled by your sendto/recvfrom...
For more details, I post some code here. I used MFC to develop GUI, so, the extracted code is not very neat :) and for simplicity, I don't mention some trivial code.
This is code of AppA
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
// create socket to send message
socketa = socket(AF_INET, SOCK_DGRAM, PF_UNSPEC);
char opt[2];opt[0] = 1;opt[1] = 0;
setsockopt(socketa, SOL_SOCKET, SO_BROADCAST, opt, sizeof(opt)); // Broadcast socket
// use broadcast address
IN_ADDR addr; // 255,255,255,255; don't mention here
SOCKADDR_IN sendaddress;
sendaddress.sin_addr = addr;
sendaddress.sin_family = AF_INET;
sendaddress.sin_port = htons(8009);
// this is code to send message
char buf[] = "hello world!"; // in fact, i get it from a textbox
int len = (int) strlen(buf);
sendto(socketa, (char FAR *)buf, len, 0,(conststruct sockaddr FAR *)&sendaddress, sizeof(sendaddress));
This is how my program run, but only one-way communication. I tried to make it two-way, using the same socket. But how can I make it? I try to make some code, but it always throws very-hard-to-read-and-debug Exception. In fact, I think I can't debug when any Exception is thrown in C++ :((
Can you help me? I think it's a basic technique with someone who familiar with c++ and socket. Please help me out with some code. Thanks!!!