First, the general steps of TCP programming
Server-side:
1. Create a socket with a function socket ()
2, binding IP address, port and other information to the socket, with the function bind ()
3, open monitoring, with function listen ()
4, receive the connection from the client, with the function accept ()
5, send and receive data, with function Send () and recv (), or read () and write ()
6. Close the network connection
7. Turn off monitoring
Client:
1. Create a socket with a function socket ()
2, set the IP address and port to connect the other properties
3, connect the server, with function connect ()
4, send and receive data, with function Send () and recv (), or read () and write ()
5. Close the network connection
The following is a sequence diagram of TCP traffic:
Second, the general procedure of UDP programming
Server:
1. Create a socket with a function socket ()
2, binding IP address, port and other information to the socket, with the function bind ()
3, the loop receives the data, uses the function recvfrom ()
4. Close the network connection
Client:
1. Create a socket with a function socket ()
2, set the other IP address, port and other properties
3, send data, with function sendto ()
4. Close the network connection
Here is the timing diagram for UDP communication:
Third, the difference between Windows sockets and Linux socket programming
1. header file
Under Windows Winsocket.h/winsocket2.h
Winsocket2.0 needs ws2_32.lib and Ws2_32.dll.
Linux under Sys/socket.h
Error handling: Errno.h
2. Initialization
WSAStartup required under Windows
Linux does not require
3. Close socket
Under Windows Closesocket
Linux under Close
4. Type
Under Windows socket
Linux under int
#ifdef WIN32
typedef int SOCKLEN_T;
typedef int ssize_t;
#endif
#ifdef __linux__
typedef int SOCKET;
typedef unsigned char BYTE;
typedef unsigned long DWORD;
#define FALSE 0
#define SOCKET_ERROR (-1)
#endif
5. Get the error code
Windows GetLastError ()/wsagetlasterror ()
Linux under errno variable
6. Set non-blocking
Under Windows Ioctlsocket ()
Linux under Fcntl () <fcntl.h>
7. The last parameter of the Send function
Under Windows general set to 0
Linux is best set to msg_nosignal, if not set, after sending an error may cause the program to exit.
8, millisecond time acquisition
Under Windows GetTickCount ()
Linux under Gettimeofday ()
9, the subsequent use to add!!!
Four, network programming example
1. TCP Programming under Windows
Server:
#include "stdafx.h"
#include <WinSock2.h>
#include <iostream>
using namespace Std;
#include <stdio.h>
int _tmain (int argc, _tchar* argv[])
{
WORD wversionrequested = Makeword (2,2);//Determine the maximum available socket version
Wsadata wsadata;//used to store WinSocket initialization information
int err = WSAStartup (wversionrequested, &wsadata);//Initialize using WinSocket DLL
if (err! = 0)
{
cout<< "WSAStartup failed!" <<endl;
}
//Step One: Create a server socket
//First parameter Select protocol family, second select data flow type, third select protocol type
Socket SOCKETSRV = socket (AF_INET,SOCK_STREAM,IPPROTO_TCP);
if (socketsrv = = invalid_socket)
{
cout<< "Create socket failed" <<endl;
}
Step two: Bind the port, IP information to the socket
Sockaddr_in addrsrv; This structure is used to store the information on the local and remote sides used to connect the socket.
Use the IP address specified by the system. Htonl converting an unsigned long-shaped host into a TCP/IP network byte-order (big-endian)
Addrsrv.sin_addr. S_un. S_ADDR = htonl (Inaddr_any);
addrsrv.sin_family = af_inet;
Addrsrv.sin_port = htons (8888);//htons converts an unsigned short-integer port host byte sequence into a TCP/IP network byte order (big-endian)
if (int n = bind (Socketsrv, (sockaddr*) &addrsrv,sizeof (sockaddr)))
{
cout<< "BIND server socket failed" <<endl;
}
Step Three: Monitor
if (Listen (socketsrv,somaxconn))///The second parameter is the maximum acceptable number of connection requests
{
cout<< "Listen failed" <<endl;
}
Step four: Receive client connections
Sockaddr_in addrclient;//used to store customer connection information
int nlen = sizeof (SOCKADDR);
Char buf1[255] = "";//the client IP and port information string that holds the connection
Char buf2[255] = "";//Receive and send buffered data
Char bufrecv[255] = "";
This nlen doesn't set an initial value, and it goes wrong.
SOCKET Socketcon = Accept (Socketsrv, (sockaddr*) &addrclient,&nlen);//After changing to multi-threaded, you can connect to multi-person conversations
while (true)
{
Inet_ntoa converts the IPV4 network address into a standard, point-and-click String (for example: 192.168.1.1)
Ntohs the unsigned short-integer network byte order to the unsigned short-integer host byte order, as opposed to the above htons
sprintf (BUF1, "***ip:%s port:%d #\n", Inet_ntoa (ADDRCLIENT.SIN_ADDR), Ntohs (Addrclient.sin_port));
//Step five: Receive and transmit data
int NBYTESRECV = recv (socketcon,bufrecv,sizeof (BUFRECV), 0);
if (strcmp (Bufrecv, "exit") = = 0)
{
//closesocket (socketcon);
break;
}
strcat (BUF1,BUFRECV);
cout<<buf1<<endl;
cout<< "* * * you#: "<<endl;
//cin>>buf2;
cin.getline (buf2,sizeof (BUF2));
int nbytessent = Send (Socketcon,buf2,sizeof (BUF1), 0);
}
Step Six: Close the connection
Closesocket (Socketcon);
Closesocket (SOCKETSRV);
WSACleanup ();//terminating using WinSocket DLL
return 0;
}
Client:
#include "stdafx.h"
#include <WinSock2.h>
#include <iostream>
using namespace Std;
int _tmain (int argc, _tchar* argv[])
{
WORD wversionrequested = Makeword (2,2);
Wsadata Wsadata;
if (WSAStartup (Wversionrequested,&wsadata))
{
cout<< "WSAStartup failed" <<endl;
}
Step one: Create a socket
Socket socktclient = socket (af_inet, sock_stream,ipproto_tcp);
Step two: Set the IP, port and other information of the other person to connect
Sockaddr_in addrclient;
Inet_addr Converting a dot-format IP string into a form suitable for the IN_ADDR structure
Addrclient.sin_addr. S_un. S_ADDR = inet_addr ("127.0.0.1");
addrclient.sin_family = af_inet;
Addrclient.sin_port = htons (8888);
Step three: Connect to the server
if (Connect (socktclient, (sockaddr*) &addrclient,sizeof (sockaddr)))
{
cout<< "Connect Failed" <<endl;
}
Char buf[255] = "";
while (true)
{
// Step four: Send and receive data
cout<< "***you#" <<ENDL;
//cin>>buf;
cin.getline (buf,sizeof (BUF));
if (strcmp (buf, "exit") = = 0)
{
break;
}
int nbytessent = Send ( Socktclient,buf,sizeof (BUF), 0);
int nbytesrecv = recv (socktclient,buf,sizeof (BUF), 0);
cout<< "***server#" <<endl;
cout<<buf<<endl;
}
Step five: Close the connection
Closesocket (socktclient);
return 0;
}
2. UDP programming under Windows
Server:
#include "stdafx.h"
#include <WinSock2.h>
#include <iostream>
using namespace Std;
int _tmain (int argc, _tchar* argv[])
{
WORD wversionrequested = Makeword (2,2);
Wsadata Wsadata;
WSAStartup (Wversionrequested,&wsadata);
Step one: Create a socket
Socket SOCKETSRV = socket (AF_INET,SOCK_DGRAM,IPPROTO_UDP);//This is replaced by non-connection-oriented datagram mode
Sockaddr_in addrsrv;
Addrsrv.sin_addr. S_un. S_ADDR = htonl (Inaddr_any);
addrsrv.sin_family = af_inet;
Addrsrv.sin_port = htons (8000);
Step two: Bind the port, IP and other information to the socket
if (Bind (Socketsrv, (sockaddr*) &addrsrv,sizeof (sockaddr)))
{
cout<< "Bind failed" <<endl;
}
Char buf[255] = "";
while (true)
{
Sockaddr_in addrclient;//used to store customer connection information
int nlen = sizeof (SOCKADDR);
Step three: Receive data
int nbytesrecv = Recvfrom (socketsrv,buf,sizeof (BUF), 0, (sockaddr*) &addrclient,&nlen);//There will be an error without variable storage
if (strcmp (buf, "exit") = = 0)
{
Closesocket (addrclient);
Continue
}
cout<< "client#" <<endl;
cout<<buf<<endl;
}
Step four: Turn off network connection
Closesocket (SOCKETSRV);
WSACleanup ();
return 0;
}
Client:
#include "stdafx.h"
#include <WinSock2.h>
#include <iostream>
using namespace Std;
int _tmain (int argc, _tchar* argv[])
{
WORD wversionrequested = Makeword (2,2);
Wsadata Wsadata;
WSAStartup (Wversionrequested,&wsadata);
Step one: Create a socket
Socket socketclient = socket (AF_INET,SOCK_DGRAM,IPPROTO_UDP);//This is replaced by non-connection-oriented datagram mode
Step Two: Set the address information to the recipient of the data
Sockaddr_in Addrto;
Addrto.sin_addr. S_un. S_ADDR = inet_addr ("127.0.0.1");
addrto.sin_family = af_inet;
Addrto.sin_port = htons (8000);
Char buf[255] = "";
while (true)
{
cout<< "you#" <<endl;
Cin.getline (buf,sizeof (BUF));
if (strcmp (buf, "exit") = = 0)
{
Break
}
Step three: Send data
int nbytessent = SendTo (Socketclient, Buf,strlen (BUF) +1,0, (sockaddr*) &addrto,sizeof (sockaddr));
}
Step four: Turn off network connection
Closesocket (socketclient);
WSACleanup ();
return 0;
}
3. TCP Programming under Linux
Server:
Client:
2. UDP programming under Linux
Server:
Client:
TCP/UDP Basics and basic examples of network programming (Windows and Linux)