标签:
基于linux,该实例实现了服务端传了一个hello world给客户端。
socket()创建socket
bind()绑定socket到IP地址和端口
listen()服务器监听客户端的连接
connect()客户端连接到服务器
accept()应用程序接受完成3次握手的客户端连接
send() recv() write() read()机器间相互发送数据
close() 关闭socket
gethostbyname() gethostbyaddr() V4专有
select() poll() 处理多个连接的读、写和错误状态
getsockopt()得到对应socket的选项值
setsockopt()设置对应socket的选项值
具体代码如下:
服务端部分:
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int main(int argc, char** argv)
{
char hello[] = "hello world";
struct sockaddr_in sa;
int SocketFD = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
if (-1 == SocketFD) {
perror("cannot create socket");
exit(EXIT_FAILURE);
}
memset(&sa, 0, sizeof sa);
sa.sin_family = AF_INET;
sa.sin_port = htons(2222);
sa.sin_addr.s_addr = htonl(INADDR_ANY);
if (-1 == bind(SocketFD, (struct sockaddr*)&sa, sizeof sa)) {
perror("bind failed");
close(SocketFD);
exit(EXIT_FAILURE);
}
if (-1 == listen(SocketFD, 10)) {
perror("listen failed");
close(SocketFD);
exit(EXIT_FAILURE);
}
for (;;) {
int ConnectFD = accept(SocketFD, NULL, NULL);
if (0 > ConnectFD) {
perror("accept failed");
close(SocketFD);
exit(EXIT_FAILURE);
}
int writeSize = 0;
size_t totalWrite = 0;
while (totalWrite < sizeof(hello)) {
writeSize =
write(ConnectFD, hello + totalWrite, sizeof(hello) - totalWrite);
if (-1 == writeSize) {
perror("write failed");
close(ConnectFD);
close(SocketFD);
exit(EXIT_FAILURE);
}
totalWrite += writeSize;
}
if(-1==shutdown(ConnectFD,SHUT_RDWR)){
perror("shutdown failed");
close(ConnectFD);
close(SocketFD);
exit(EXIT_FAILURE);
}
close(ConnectFD);
}
close(SocketFD);
return EXIT_SUCCESS;
}
客户端部分:
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int main(int argc, char** argv)
{
char hello[] = "hello world";
struct sockaddr_in sa;
int SocketFD = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
if (-1 == SocketFD) {
perror("cannot create socket");
exit(EXIT_FAILURE);
}
memset(&sa, 0, sizeof sa);
sa.sin_family = AF_INET;
sa.sin_port = htons(2222);
res = inet_pton(AF_INET, "127.0.0.1", &sa.sin_addr);
if (-1 == connect(SocketFD, (struct sockaddr*)&sa, sizeof sa)) {
perror("connect failed");
close(SocketFD);
exit(EXIT_FAILURE);
}
char buffer[512];
int totalRead = 0;
for (;;) {
int readSize = 0;
readSize = read(SocketFD, buffer + totalRead, sizeof(buffer) - totalRead);
if (readSize == 0) {
break;
}
else if (readSize == -1) {
perroe("read failed");
close(SocketFD);
exit(EXIT_FAILURE);
}
totalRead += readSize;
}
buffer[totalRead] = 0;
printf("get from server:%s\n", buffer);
(void)shutdown(SocketFD, SHUT_RDWR);
close(SocketFD);
return EXIT_SUCCESS;
}
客户端和服务端哪一边主动的调用了close函数,哪一边进入TIME_WAIT
socketAPI:一个最简单的服务器和对应的客户端C语言的实现
标签:
原文地址:http://www.cnblogs.com/liumt/p/5885968.html