C语言Socket实现网络通信

本文详细介绍了如何使用C语言的Socket在Windows环境下实现网络通信。从加载Winsock库开始,涉及套接字的创建与释放、绑定IP地址和端口、服务器监听与客户端连接、数据收发以及关闭连接等关键步骤。通过示例代码server.cpp和client.cpp,进行了实际的测试验证。
摘要由CSDN通过智能技术生成

document.txt
*套接字通信流程
Winsock库的加载和卸载
要使用Windows Socket API进行编程,首先必须调用WSAStartup()函数初始化Winsock动态库。
int WSAStartup(WORD wVersionRequested, LPWSADATA lpWSAData);
参数一wVersionRequested:为我们要求初始化的Winsock版本号
参数二lpWSAData:为实际初始化成功的WSA(Windows Socket API)版本信息。
在程序末尾,需调用int WSACleanup(void)函数卸载Winsock动态库。
套接字的创建和释放
首先必须调用socket()函数创建一个套接字描述符
// The socket function creates a socket that is bound to a specific service provider.
SOCKET socket(int af,// [in] Address family specification.
int type,// [in] Type specification for the new socket.
int protocol// [in] Protocol to be used with the socket that is specific to the indicated address family.
);
套接字的释放
当不使用socket()创建的套接字时,应该调用closesocket()函数将它关闭
// The closesocket function closes an existing socket.
int closesocket(
SOCKET s// [in] Descriptor identifying the socket to close.
);
绑定套接字到指定的IP地址和端口
对于传输套接字,在执行收发数据前需要对本地端口进行绑定
// The bind function associates a local address with a socket.
int bind(
SOCKET s, // [in] Descriptor identifying an unbound socket.
const struct sockaddr FAR *name, // [in] Address to assign to the socket from the SOCKADDR structure.
int namelen // [in] Length of the value in the name parameter.
);
bind()函数用在套接字连接建立之前,它的作用是绑定面向连接(connection oriented)的或者面向无连接
(transaction oriented)的套接字。当一个套接字被socket函数创建以后,它存在于指定的地址家族里,
但是它是匿名的。bind()函数通过安排一个本地名称到未命名的socket建立此socket的本地关联。
本地名称包含3个部分:主机地址、协议号(TCP或UDP)和端口号。
TCP服务器设置套接字进入监听状态
// The listen function places a socket a state where it is listening for an incoming connection.
int listen(
SOCKET s,// [in] Descriptor identifying a bound, unconnected socket.
int backlog// [in] Maximum length of the queue of pending connections.
);
服务器为了接受连接,首先使用socket()函数创建一个套接字,然后使用bind()函数将它绑定到一个本地地址(端口),
再用listen()函数为到达的连接指定一个backlog。
backlog参数指定了正在等待连接的最大队列长度。
客户端主动连接
// The connect function establishes a connection to a specified socket.
int connect(
SOCKET s,// [in] Descriptor identifying an unconnected socket.
const struct sockaddr FAR *name,// [in] Name of the socket to which the connection should be established.
int namelen// [in] Length of name.
);
客户端是连接的发起者(initiate),它通过调用connect()

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值