Introduction
This article demonstrates how to send and receive data using TCP/IP in VC++.NET. This alsow describes how to use threads and how to use costom post messages to communicate with threads.
Background
This article uses CSocket
object to communicate and WM_USER kind post messages to communicate with the thread. This also uses worker threads.
Creating the thread
The thread is created by using AfxBeginThread(ReceiveMessage,&m_EDT_Port)
. This function has two overloads. One to call UI threads and one to call worker threads. We are using a worker thread here. In here "ReceiveMessage" means the function the thread is going to perform and "&m_EDT_Port" means that I'm passing the port number taken from the edit control to the function.
Receive and Send
In this sample program I've used a server socket to receive and a client socket to send. But you can do vice versa. That means you can call CSocket.Send()
and CSocket.Receive
with both server and client sockets. The thing is you need a server socket in one side and a client socket in the other side to establish the communication. Once you establish the connection you can send and receive from both the client and the server socket.
Receive
CSocket* sockServ;
CSocket* sockRecv;
The above variables are defined globally
CSocket sockServT;
CSocket sockRecvT;
sockServ = &sockServT;
sockRecv = &sockRecvT;
State = sockServ->Create(PortNo);
sockServ->Listen();
sockServ->Accept(*sockRecv);
RecvData=new char[500];
int len = sockRecv->Receive(RecvData ,500);
In this block only the required lines of code is shown. In the sample program you will find the other definitions and stuff
Here as you can see we have used a server socket and we first create it with the port number. Then we start listening in that port number. Then we accept the port in a nother socket and use that socket to receive the data. Keep in mind that you can use the same port to send the data too.
Send
sockClient.Create();
sockClient.Connect(IP,Port);
DataSend=new char[Data.GetLength()];
DataSend=Data.GetBuffer();
sockClient.Send(DataSend,Data.GetLength());
sockClient.Close();
As you can see sending using a client socket as simple as this. Just connect the client usint the IP and port and you can start sending or receiving.
So thats it for sending and receiving using TCP