首先我要了解IOS模型,之前两年都在学这个模型我已经熟悉了。其次是socket API, 进程和线程的并行。
sockets API:
Linux中的网络通过socket接口实现,socket是一种特殊的IO,也是一个file discriptor。一个完整的sockets都有一个相关的描述(协议,本地地址,本地端口,远程地址,远程端口)。每个端口都有本地唯一的sockets号,由系统分配。
- 应用: #incldue
int socket(int domain,int type, int protocol)
int domain:AF_INET =>internet IPv4
AF_INET6 = IPv6
int type: SOCK_STREAM = transfer in bytes stream
SOCK_DGRAM = transfer in bytes stream without checking
int protocol: 0 = lets system choose which protocol will be used.
-基本套接字系统调有有如下一些:
创建套接字: socket()
绑定本机端口: bind()
建立连接: connect(),accept()
侦听端口: listen()
数据传输: send(), recv()
输入/输出多路复用: select()
关闭socket: closesocket()
-数据类型 struct sockaddr {
unsigned short sa_family; //地址族, 一般为AF_INET
char sa_data[14]; //14字节的协议地址 }
struct sockaddr_in {
short int sin_family; //地址族
unsigned short int sin_port; //端口号
struct in_addr in_addr; //ip地址
unsigned char sin_zero[8]; //填充
}
用socket函数传入地址时要注意字节序转换,每个机器的字节存储顺序不一样,但网络通信时需要统一标准,我们可以用
htons()---host to network short
htonl()---host to network long
ntohs() and ntohl reverse.
线程
-创建(成功返回0,否则返回错误编号)
int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg);
tidp:线程标识符
attr:线程属性设置
start_rtn:线程函数起始地址
arg:传递给start_rtn函数的参数
how create a TCP server:
1. create a socket and configure the IP address and port by struct -- socketaddr_in
2. bind the IP and port
3. listen the signal, tell the client that server is ready to deal requests
4. build a link with requests from clients
5. put these requests into a listen queue and choose one to deal with by function accept()
6. for the request which is dealing with, we can read and write ....
No comments:
Post a Comment