欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

socket通信实现

程序员文章站 2022-07-07 15:15:10
...

为了实现socket的通信验证,写了一个简单的客服端向服务器端通信的代码
服务器端:
1、版本验证

WORD wVersionRequested=MAKEWORD(2,2);
 WSADATA result;
 int err = WSAStartup(wVersionRequested, &result);
 if (err != 0) {
  printf("启动失败\n");
  WSACleanup();
  return 404;
 }
 if (LOBYTE(result.wVersion) != 2 || HIBYTE(result.wVersion) != 2) {
  printf("版本号获取失败!\n");
  WSACleanup();
  return 404;
 }

2、生成socket

SOCKET ser_sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
 if (INVALID_SOCKET == ser_sock) {
  printf("生成socket失败!\n");
  WSACleanup();
  return 404;
 }

3、套接字绑定

struct sockaddr_in ser_addr;
 memset(&ser_addr, 0, sizeof(ser_addr));
 ser_addr.sin_family = AF_INET;
 ser_addr.sin_addr.s_addr = inet_addr("192.168.1.104");
 ser_addr.sin_port = htons(10000);//端口转为大端字节序
 
 int back=bind(ser_sock,(SOCKADDR*) &ser_addr,sizeof(ser_addr));
 if (SOCKET_ERROR == back) {
  printf("绑定失败!\n");
  WSACleanup();
  return 404;
 }

4、监听连接及接收;接受失败即关闭

 //监听
 int re = listen(ser_sock,10);
 if (SOCKET_ERROR == re) {
  printf("监听失败!\n");
  WSACleanup();
  return 404;
 }
 //接收
 printf("等待连接。。。。\n");
 SOCKET jie = accept(ser_sock, NULL,NULL);
 if (INVALID_SOCKET == jie) {
  printf("连接失败!\n");
  closesocket(ser_sock);
  WSACleanup();
  return 404;
 }
 printf("连接成功!\n");

5、通信

char buff[1024];
 while(1) {
  int r = recv(jie, buff, 1023, NULL);
  if (r > 0) {
   buff[r] = 0;
   printf(">>>>%s\n",buff);
  }
 }

客户端:
几乎流程与上述相同只是不需要绑定、监听,接受步骤,直接改为连接和通信
代码实现:

WORD wVersionRequested = MAKEWORD(2, 2);
 WSADATA result;
 int err = WSAStartup(wVersionRequested, &result);
 if (err != 0) {
  printf("启动失败\n");
  WSACleanup();
  return 404;
 }
 if (LOBYTE(result.wVersion) != 2 || HIBYTE(result.wVersion) != 2) {
  printf("版本号获取失败!\n");
  WSACleanup();
  return 404;
 }
 //生成套接字
 SOCKET cli_sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
 if (INVALID_SOCKET == cli_sock) {
  printf("生成socket失败!\n");
  WSACleanup();
  return 404;
 }
 //设备信息
 struct sockaddr_in ser_addr;
 memset(&ser_addr, 0, sizeof(ser_addr));
 ser_addr.sin_family = AF_INET;
 ser_addr.sin_addr.s_addr = inet_addr("192.168.1.104");
 ser_addr.sin_port = htons(10000);//端口转为大端字节序
//连接
 int co = connect(cli_sock, (SOCKADDR*)&ser_addr, sizeof(ser_addr));
 printf("正在建立连接。。。。。\n");
 if (SOCKET_ERROR == co) {
  printf("连接失败!\n");
  closesocket(cli_sock);
  WSACleanup();
  return 404;
 }
 printf("连接成功!\n");
 //通信
 char buff[1024];
 while (1)  {
  memset(buff, 0, 1024);
  printf("你要发送的内容:\n");
  scanf("%s", buff);
  send(cli_sock,buff,strlen(buff),NULL);
 }

socket通信实现
socket通信实现

相关标签: socket