Sample socket communication program

本文介绍了一种使用UDP协议实现客户端与服务器间Socket通信的方法。通过示例代码详细展示了如何设置服务器端口、发送与接收数据的过程。对于理解基本的网络编程原理及实现具有很好的参考价值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

I am testing differnent Model of using socket communiton. In my opinion, there are many ways we can use. Now i will test different communication model . I will try my best to samplified it. One way is as follows:

Server:

 ::CSocket S,S2;
 ::SOCKADDR sr ;
 S.Create(1088);
 S.Bind(1088,L"192.168.0.40");
 S.Listen(6);
 S.Accept(S2,&sr);
 char p[]="ASDF";
 S2.Send(L"dddddd",14);

Client:

  ::CSocket s;
  s.Create();
 s.Connect(L"192.168.0.40",1088);
 WCHAR buf[32] = { 0 };
 s.Receive(buf,32);
 me.SetWindowText(buf);

You can use socket achieving this aim :

Client:

// TServer.cpp : Defines the entry point for the console application.
// socket server

#include "stdafx.h"
#include <WINSOCK2.H>
#include <iostream>
#pragma comment(lib, "ws2_32.lib")
using namespace std;
int main(int argc, char* argv[])
{
 
 WORD uVersionInfo;
 WSADATA wdata;
 uVersionInfo = MAKEWORD(1,1);
 if(!WSAStartup(uVersionInfo,&wdata))
  cout<<"init socket lib success"<<endl;
 if(LOBYTE(wdata.wVersion) != 1 || HIBYTE(wdata.wVersion) != 1)
  cout<<"version error"<<endl;
    SOCKET s = socket(AF_INET,SOCK_DGRAM, 0);
 sockaddr_in sin;
 sin.sin_family = AF_INET;
 sin.sin_addr.S_un.S_addr = inet_addr("192.168.0.40");
 sin.sin_port = htons(1088);
// bind(s, (struct sockaddr*)&sin , sizeof(sin));
 //listen(s,5);
 char buf[10] = "abc";
 sockaddr sa;
 int len = sizeof(sin);
 //   int count = recvfrom(s, buf, 10, 0, &sa, &len);
 int count = sendto(s, buf, 10, 0, (struct sockaddr*)&sin, len);
 cout<<"sended num :"<<count<<endl;
 closesocket(s);
 WSACleanup();
 return 0;
}
Server :

// TServer.cpp : Defines the entry point for the console application.
// socket server

#include "stdafx.h"
#include <WINSOCK2.H>
#include <iostream>
using namespace std;
int main(int argc, char* argv[])
{

 WORD uVersionInfo;
 WSADATA wdata;
 uVersionInfo = MAKEWORD(1,1);
 if(!WSAStartup(uVersionInfo,&wdata))
  cout<<"init socket lib success"<<endl;
 if(LOBYTE(wdata.wVersion) != 1 || HIBYTE(wdata.wVersion) != 1)
  cout<<"version error"<<endl;
    SOCKET s = socket(AF_INET,SOCK_DGRAM, 0);
 sockaddr_in sin;
 sin.sin_family = AF_INET;
 sin.sin_addr.S_un.S_addr = inet_addr("192.168.0.40");
 sin.sin_port = htons(1088);
 bind(s, (struct sockaddr*)&sin , sizeof(sin));
 //listen(s,5);
 char buf[10];
 sockaddr sa;
 int len = sizeof(sa);
    int count = recvfrom(s, buf, 10, 0, &sa, &len);
 cout<<"receive num :"<<count<<"mes"<<buf<<endl;
 closesocket(s);
 WSACleanup();
 return 0;
}
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值