首页 > C++基础--简单Socket通信实例

C++基础--简单Socket通信实例

// WindowsSocketServer.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include 
#include 
#include #pragma comment(lib,"Ws2_32.lib")using namespace std;
#define PORT 8081
#define IP_ADDRESS "172.16.20.181"
DWORD WINAPI ClientThread(LPVOID lpParameter){SOCKET ClientSocket = (SOCKET)lpParameter;int Ret = 0;char RecvBuffer[MAX_PATH];while ( true ){memset(RecvBuffer, 0x00, sizeof(RecvBuffer));Ret = recv(ClientSocket, RecvBuffer, MAX_PATH, 0);if ( Ret == 0 || Ret == SOCKET_ERROR ) {cout<<"客户端退出!"<<endl;break;}cout<<"接收到客户信息为:"<endl;// send msg to clientRet = send(ClientSocket, RecvBuffer, (int)strlen(RecvBuffer), 0);if ( Ret == SOCKET_ERROR ){cout<<"Send Info Error::"<endl;break;}cout<<"After Send Msg:"<endl;}return 0;}int main(int argc, char* argv[]){WSADATA  Ws;SOCKET ServerSocket, ClientSocket;struct sockaddr_in LocalAddr, ClientAddr;int Ret = 0;int AddrLen = 0;HANDLE hThread = NULL;//Init Windows Socket//The WSAStartup function initiates use of WS2_32.DLL by a process.if ( WSAStartup(MAKEWORD(2,2), &Ws) != 0 ){cout<<"Init Windows Socket Failed::"<endl;return -1;}//Create SocketServerSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);if ( ServerSocket == INVALID_SOCKET ){cout<<"Create Socket Failed::"<endl;return -1;}//the address of family specificationLocalAddr.sin_family = AF_INET;//The inet_addr function converts a string containing an (Ipv4) Internet Protocol dotted address into a proper address for the IN_ADDR structure.LocalAddr.sin_addr.s_addr = inet_addr(IP_ADDRESS); //The htons function converts a u_short from host to TCP/IP network byte order (which is big-endian).LocalAddr.sin_port = htons(PORT);//Sets buffers to a specified character.memset(LocalAddr.sin_zero, 0x00, 8);//Bind Socket,The bind function associates a local address with a socket.Ret = bind(ServerSocket, (struct sockaddr*)&LocalAddr, sizeof(LocalAddr));if ( Ret != 0 ){cout<<"Bind Socket Failed::"<endl;return -1;}//The listen function places a socket in a state in which it is listening for an incoming connection.Ret = listen(ServerSocket, 10);if ( Ret != 0 ){cout<<"listen ClientSocket Failed::"<endl;return -1;}cout<<"服务端已经启动"<<endl;while ( true ){AddrLen = sizeof(ClientAddr);//The accept function permits an incoming connection attempt on a socket.ClientSocket = accept(ServerSocket, (struct sockaddr*)&ClientAddr, &AddrLen);if ( ClientSocket == INVALID_SOCKET ){cout<<"Accept Failed::"<endl;break;}//The inet_ntoa function converts an (Ipv4) Internet network address into a string in Internet standard dotted format.cout<<"客户端连接::"<":"<endl;//Call this function to create a thread that can use CRT functions.hThread = CreateThread(NULL, 0, ClientThread, (LPVOID)ClientSocket, 0, NULL);if ( hThread == NULL ){cout<<"Create Thread Failed!"<<endl;break;}CloseHandle(hThread);}closesocket(ServerSocket);closesocket(ClientSocket);WSACleanup();return 0;}
// WindowsSocketClient.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include 
#include 
#include #pragma comment(lib,"Ws2_32.lib")using namespace std;#define PORT 8081
#define IP_ADDRESS "172.16.20.181"int _tmain(int argc, _TCHAR* argv[])
{WSADATA  Ws;SOCKET ClientSocket;struct sockaddr_in ServerAddr;int Ret = 0;int AddrLen = 0;HANDLE hThread = NULL;char SendBuffer[MAX_PATH];//Init Windows Socket//The WSAStartup function initiates use of WS2_32.DLL by a process.if ( WSAStartup(MAKEWORD(2,2), &Ws) != 0 ){cout<<"Init Windows Socket Failed::"<endl;return -1;}//Create SocketClientSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);if ( ClientSocket == INVALID_SOCKET ){cout<<"Create Socket Failed::"<endl;return -1;}ServerAddr.sin_family = AF_INET;ServerAddr.sin_addr.s_addr = inet_addr(IP_ADDRESS);ServerAddr.sin_port = htons(PORT);memset(ServerAddr.sin_zero, 0x00, 8);//Bind Socket,The bind function associates a local address with a socket.//Ret = bind(ClientSocket, (struct sockaddr*)&ServerAddr, sizeof(ServerAddr));//if ( Ret != 0 )//{//    cout<<"Bind Client Socket Failed::"<//    //return -1;//}
Ret = connect(ClientSocket,(struct sockaddr*)&ServerAddr, sizeof(ServerAddr));if ( Ret == SOCKET_ERROR ){cout<<"Connect Error::"<endl;// return -1;
     }else{cout<<"连接成功!"<<endl;}while ( true ){cin.getline(SendBuffer, sizeof(SendBuffer));Ret = send(ClientSocket, SendBuffer, (int)strlen(SendBuffer), 0);if ( Ret == SOCKET_ERROR ){cout<<"Send Info Error::"<endl;break;}char recvBuf[500];int byteRecv = recv(ClientSocket, recvBuf, MAX_PATH, 0);if (byteRecv != 0){recvBuf[byteRecv] = 0;cout << "From server: " << recvBuf << endl;}}closesocket(ClientSocket);WSACleanup();system("pause");return 0;}

转载于:https://www.cnblogs.com/kingdom_0/articles/2558131.html

更多相关:

  • 在opencv中,reshape函数比较有意思,它既可以改变矩阵的通道数,又可以对矩阵元素进行序列化,非常有用的一个函数。 函数原型: C++: Mat Mat::reshape(int cn, int rows=0) const 参数比较少,但设置的时候却要千万小心。 cn: 表示通道数(channels), 如果设为0,...

  • 使用count,返回的是被查找元素的个数。如果有,返回1;否则,返回0。注意,map中不存在相同元素,所以返回值只能是1或0。 使用find,返回的是被查找元素的位置,没有则返回map.end()。 #include #include #include #include

  • 1 //改代码用于精确计算除法的位数,比如求无限循环小数的循环节 2 //求循环节时,需要定义一个数组,用与标记是否有相同的余数,若是遇到时,结束循环,即得到循环节 3 #include 4 using namespace std; 5 6 int main() { 7 int a, b...

  • 机器学习简单代码示例    //在gcc-4.7.2下编译通过。 //命令行:g++ -Wall -ansi -O2 test.cpp -o test #include using namespace std; void input(int &oper,const bool meth) {//meth为true...