Socket编程实践(3) --Socket API
socket函数
#include <sys/types.h> #include <sys/socket.h> int socket(int domain, int type, int protocol);
创建一个套接字用于通信
参数:
domain:指定通信协议族(protocol family),常用取值AF_INET(IPv4)
type:指定socket类型, 流式套接字SOCK_STREAM,数据报套接字SOCK_DGRAM,原始套接字SOCK_RAW
protocol:协议类型,常用取值0, 使用默认协议
返回值:
成功: 返回非负整数,套接字;
失败: 返回-1
bind函数
int bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen);
绑定一个本地地址到套接字
参数:
sockfd:socket函数返回的套接字
addr:要绑定的地址
//sockaddr_in结构, bind时需要强制转换成为struct sockaddr*类型
struct sockaddr_in
{
sa_family_t sin_family; /* address family: AF_INET */
in_port_t sin_port; /* port in network byte order */
struct in_addr sin_addr; /* internet address */
};
/* Internet address. */
struct in_addr
{
uint32_t s_addr; /* address in network byte order */
};
/**示例:INADDR_ANY的使用, 绑定本机任意地址**/
int main()
{
int listenfd = socket(AF_INET, SOCK_STREAM, 0);
if (listenfd == -1)
err_exit("socket error");
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(8001);
//绑定本机的任意一个IP地址, 作用同下面两行语句
addr.sin_addr.s_addr = htonl(INADDR_ANY);
//inet_aton("127.0.0.1", &addr.sin_addr);
//addr.sin_addr.s_addr = inet_addr("127.0.0.1");
if (bind(listenfd, (const struct sockaddr *)&addr, sizeof(addr)) == -1)
err_exit("bind error");
else
cout << "bind success" << endl;
}
listen函数
int listen(int sockfd, int backlog);
listen函数应该用在调用socket和bind函数之后, 并且用在调用accept之前, 用于将一个套接字从一个主动套接字转变成为被动套接字。
backlog说明:
对于给定的监听套接口,内核要维护两个队列:
1、已由客户发出并到达服务器,服务器正在等待完成相应的TCP三路握手过程(SYN_RCVD状态)
2、已完成连接的队列(ESTABLISHED状态)
但是两个队列长度之和不能超过backlog
backlog推荐使用SOMAXCONN(3.13.0-44-generic中该值为128), 使用等待队列的最大值;
Man-Page中的listen说明:
listen() marks the socket referred to by sockfd as a passive socket, that is, as a socket that
will be used to accept incoming connection requests using accept(2).
The sockfd argument is a file descriptor that refers to a socket of type SOCK_STREAM or
SOCK_SEQPACKET.
The backlog argument defines the maximum length to which the queue of pending connections for
sockfd may grow. If a connection request arrives when the queue is full, the client may receive
an error with an indication of ECONNREFUSED or, if the underlying protocol supports retransmission,
the request may be ignored so that a later reattempt at connection succeeds.
If the backlog argument is greater than the value in /proc/sys/net/core/somaxconn(Ubuntu 14.04 该值为128), then it is silently truncated to that value; the default value in this file is 128. In kernels
before 2.4.25, this limit was a hard coded value, SOMAXCONN, with the value 128.
accept函数
int accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen);
从已完成连接队列返回第一个连接(the first connection request on the queue of pending connections for the listening
socket, sockfd, creates a new connected socket, and returns a new file descriptor referring to that socket.
The newly created socket is not in the listening state),如果已完成连接队列为空,则阻塞。The original
socket sockfd is unaffected by this call.
参数:
sockfd:服务器套接字
addr:将返回对等方的套接字地址, 不关心的话, 可以设置为NULL
addrlen:返回对等方的套接字地址长度, 不关心的话可以设置成为NULL, 否则一定要初始化
返回值:
On success, these system calls return a non-negative integer that is a descriptor for the accepted
socket. On error, -1 is returned, and errno is set appropriately.
connect函数
int connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen);
建立一个连接至addr所指定的套接字
参数:
sockfd:未连接套接字
addr:要连接的套接字地址
addrlen:第二个参数addr长度
示例:echo server/client实现
//server端代码
int main()
{
int listenfd = socket(AF_INET, SOCK_STREAM, 0);
if (listenfd == -1)
err_exit("socket error");
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(8001);
addr.sin_addr.s_addr = htonl(INADDR_ANY);
if (bind(listenfd, (const struct sockaddr *)&addr, sizeof(addr)) == -1)
err_exit("bind error");
if (listen(listenfd, SOMAXCONN) == -1)
err_exit("listen error");
char buf[512];
int readBytes;
struct sockaddr_in clientAddr;
//谨记: 此处一定要初始化
socklen_t addrLen = sizeof(clientAddr);
while (true)
{
int clientfd = accept(listenfd, (struct sockaddr *)&clientAddr, &addrLen);
if (clientfd == -1)
err_exit("accept error");
//打印客户IP地址与端口号
cout << "Client information: " << inet_ntoa(clientAddr.sin_addr)
<< ", " << ntohs(clientAddr.sin_port) << endl;
memset(buf, 0, sizeof(buf));
while ((readBytes = read(clientfd, buf, sizeof(buf))) > 0)
{
cout << buf;
if (write(clientfd, buf, readBytes) == -1)
err_exit("write socket error");
memset(buf, 0, sizeof(buf));
}
if (readBytes == 0)
{
cerr << "client connect closed..." << endl;
close(clientfd);
}
else if (readBytes == -1)
err_exit("read socket error");
}
close(listenfd);
}
//client端代码
int main()
{
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == -1)
err_exit("socket error");
//填写服务器端口号与IP地址
struct sockaddr_in serverAddr;
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(8001);
serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
if (connect(sockfd, (const struct sockaddr *)&serverAddr, sizeof(serverAddr)) == -1)
err_exit("connect error");
char buf[512];
while (fgets(buf, sizeof(buf), stdin) != NULL)
{
if (write(sockfd, buf, strlen(buf)) == -1)
err_exit("write socket error");
memset(buf, 0, sizeof(buf));
int readBytes = read(sockfd, buf, sizeof(buf));
if (readBytes == 0)
{
cerr << "server connect closed... \nexiting..." << endl;
break;
}
else if (readBytes == -1)
err_exit("read socket error");
cout << buf;
memset(buf, 0, sizeof(buf));
}
close(sockfd);
}
附-Makefile
.PHONY: clean all
CC = g++
CPPFLAGS = -Wall -g -pthread -std=c++11
BIN = server client
SOURCES = $(BIN.=.cpp)
all: $(BIN)
$(BIN): $(SOURCES)
clean:
-rm -rf $(BIN) bin/ obj/ core
Socket编程实践(3) --Socket API的更多相关文章
- Socket编程实践(2) Socket API 与 简单例程
在本篇文章中,先介绍一下Socket编程的一些API,然后利用这些API实现一个客户端-服务器模型的一个简单通信例程.该例子中,服务器接收到客户端的信息后,将信息重新发送给客户端. socket()函 ...
- Socket编程实践(2) --Socket编程导引
什么是Socket? Socket可以看成是用户进程与内核网络协议栈的接口(编程接口, 如下图所示), 其不仅可以用于本机进程间通信,可以用于网络上不同主机的进程间通信, 甚至还可以用于异构系统之间的 ...
- C# socket编程实践
C# socket编程实践——支持广播的简单socket服务器 在上篇博客简单理解socket写完之后我就希望写出一个websocket的服务器了,但是一路困难重重,还是从基础开始吧,先搞定C# ...
- Socket编程实践(6) --TCP服务端注意事项
僵尸进程处理 1)通过忽略SIGCHLD信号,避免僵尸进程 在server端代码中添加 signal(SIGCHLD, SIG_IGN); 2)通过wait/waitpid方法,解决僵尸进程 sign ...
- Socket编程实践(6) --TCPNotes服务器
僵尸进程过程 1)通过忽略SIGCHLD信号,避免僵尸进程 在server端代码中加入 signal(SIGCHLD, SIG_IGN); 2)通过wait/waitpid方法.解决僵尸进程 sign ...
- Socket编程实践(10) --select的限制与poll的使用
select的限制 用select实现的并发服务器,能达到的并发数一般受两方面限制: 1)一个进程能打开的最大文件描述符限制.这可以通过调整内核参数.可以通过ulimit -n(number)来调整或 ...
- Socket编程实践(1) 基本概念
1. 什么是socket socket可以看成是用户进程与内核网络协议栈的编程接口.TCP/IP协议的底层部分已经被内核实现了,而应用层是用户需要实现的,这部分程序工作在用户空间.用户空间的程序需要通 ...
- C# socket编程实践——支持广播的简单socket服务器
在上篇博客简单理解socket写完之后我就希望写出一个websocket的服务器了,但是一路困难重重,还是从基础开始吧,先搞定C# socket编程基本知识,写一个支持广播的简单server/clie ...
- C# Socket编程(4)初识Socket和数据流
经过前面基础知识作为背景,现在对Socket编程进行进一步的学习.在System.Net.Socket命名空间提供了Socket类,利用该类我们可以直接编写Socket的客户端和服务的的程序.但是直接 ...
随机推荐
- day07 Cookie 和 Session(非常重要)
day07 Cookie 和 Session 1. 会话技术 2. cookie 的方法和 cookie 案例-显示用户上次访问网站的时间 3. cookie 的细节 - 删除 cookie 4. S ...
- ubuntu 卸载从源码安装的 emacs
由于配置问题想卸了重装. 解压并进入你的源码所在目录: ./configure sudo make uninstall Done Reference: http://askubuntu.com/que ...
- 服务器&阵列卡LSI SAS223&组raid 10
组raid10 如配置: raid LSI SAS2236 双E5-2450L 96G 4*1TB 要求: 至少4块HDD 将接上Raid card的机器开机,根据提示按组合键进入Raid配置界面 ...
- Linux shell爬虫实现树洞网自动回复Robot
奇怪的赞数 人生在世,不如意事十之八九,可与言者无二三人.幸好我们生在互联网时代,现实中找不到可以倾诉的人还可以在网络上寻找发情绪宣泄口,树洞这类产品就是提供一个让人在网络上匿名倾诉的平台. 我是偶然 ...
- Sybase identity 字段
1.identity Oracle, DB2, pgSQL中都有sequence的概念,这个概念比Identity先进很多,在Sybase中没有Sequence对象,与之相对应的是Identity 2 ...
- ANT不完全总结,包含各种命令,ant例子等,转自:http://lavasoft.blog.51cto.com/62575/87306
ANT不完全总结 好久没有用Ant了,最近让MyEclipse.JBuilder2008逼的重回Ant上了.手生了,写了一个脚本后,重新总结下.参考了官方的文档和网上一些资料. 一.ANT的介 ...
- Android自定义View(三、深入解析控件测量onMeasure)
转载请标明出处: http://blog.csdn.net/xmxkf/article/details/51490283 本文出自:[openXu的博客] 目录: onMeasure什么时候会被调用 ...
- SQLite 附加数据库(http://www.w3cschool.cc/sqlite/sqlite-attach-database.html)
SQLite 附加数据库 假设这样一种情况,当在同一时间有多个数据库可用,您想使用其中的任何一个.SQLite 的 ATTACH DTABASE 语句是用来选择一个特定的数据库,使用该命令后,所有的 ...
- lucene查询索引库、分页、过滤、排序、高亮
2.查询索引库 插入测试数据 xx.xx. index. ArticleIndex @Test public void testCreateIndexBatch() throws Exception{ ...
- GridView如何适配不同屏幕
GridView和ListView一样,都是项目中常用的控件之一,那么本篇文章要讲的是GridView如何适应不同大小的屏幕,首先,我们来看一张效果图,如下: 每行为四个item,上下左右间距大概2d ...