SOCKET编程总结
1.初始化socket环境,创建socket
2.梆定一个端口
3.开始监听
4.接收客户端
5.接收到客户端之后,使用这个socket来与这个客户通信
#include "stdAfx.h"
#include <winsock2.h>
#include <mswsock.h>
#include <iostream>
using namespace std;
#pragma comment(lib, "ws2_32.lib")
#pragma comment(lib, "mswsock.lib")
DWORD IniSOCKDLL()
{
WORD wVersionRequested;
WSADATA wsaData;
int err=0;
wVersionRequested = MAKEWORD( 2, 2 );
err = WSAStartup( wVersionRequested, &wsaData );
return err;
}
int main(int argc, char* argv[])
{
cout<<"程序开始"<<endl;
IniSOCKDLL();
SOCKET ss=WSASocket(AF_INET,
SOCK_STREAM,
0,
NULL,
0,
NULL);
SOCKADDR_IN addr;
int len;
addr.sin_family=AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_ANY);
addr.sin_port = htons(1002);
len=sizeof(addr);
bind(ss , (PSOCKADDR)&addr , len);
listen(ss,5);
SOCKET sc=accept(ss,(PSOCKADDR)&addr,&len);
char buff[1024];
ZeroMemory(buff,1024);
recv(sc,buff,1024,0);
cout<<buff<<endl;
ZeroMemory(buff,1024);
memcpy(buff,"123",3);
send(sc,buff,3,0);
closesocket(sc);
closesocket(ss);
return 0;
}
客户端:
1.初始化socket环境,创建socket
2.连接服务端
3.开启一个线程来接收数据
4.使用send直接发数据包
#include "stdAfx.h"
#include <winsock2.h>
#include <mswsock.h>
#include <iostream>
using namespace std;
#pragma comment(lib, "ws2_32.lib")
#pragma comment(lib, "mswsock.lib")
DWORD IniSOCKDLL()
{
WORD wVersionRequested;
WSADATA wsaData;
int err=0;
wVersionRequested = MAKEWORD( 2, 2 );
err = WSAStartup( wVersionRequested, &wsaData );
return err;
}
int main(int argc, char* argv[])
{
IniSOCKDLL();
SOCKET sc=WSASocket(AF_INET,
SOCK_STREAM,
0,
NULL,
0,
NULL);
SOCKADDR_IN addr;
int len;
addr.sin_family=AF_INET;
addr.sin_addr.s_addr = inet_addr("127.0.0.1");
addr.sin_port = htons(1002);
len=sizeof(addr);
connect(sc, (struct sockaddr *)&addr, len);
char buff[1024];
ZeroMemory(buff,1024);
memcpy(buff,"123",3);
send(sc,buff,3,0);
recv(sc,buff,1024,0);
cout<<buff<<endl;
closesocket(sc);
return 0;
}
由这个我们可以做一个这样的模型:
为每个阻塞函数开一个线程,让它来处理。
这就要留意退出的时候把这一些线程给关闭