套接字
Linux中的网络编程通过socket接口实现。Socket既是一种特殊的IO也是一种文件描述符。套接字有三种:流式套接字(TCP)、数据报套接字(UDP)、原始套接字
字节序列转换
因为每一个机器内部对变量的字节存储顺序不同,而网络传输的数据大家是一定要统一顺序的。
服务端和客户端使用TCP协议流程图
服务端和客户端使用UDP协议流程图
Example
基础编程
client
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#include <arpa/inet.h>
#include <pthread.h>
#define SERVER_PORT 1234
int main(int argc, char *argv[])
{
char rBuf[20];
int socketFd;
struct sockaddr_in s_serverAddr;
socketFd = socket(AF_INET, SOCK_STREAM, 0);
if (socketFd < 0)
{
perror("socket:");
exit(-1);
}
printf("socket success! \n");
s_serverAddr.sin_family = AF_INET;
s_serverAddr.sin_port = htons(SERVER_PORT);
s_serverAddr.sin_addr.s_addr = inet_addr(argv[1]);
if (connect(socketFd, (struct sockaddr *)&s_serverAddr, sizeof(s_serverAddr)) < 0)
{
perror("connect:");
exit(0);
}
printf("connect success!\n");
int senlen = send(socketFd, "hello world", sizeof("hello world") + 1, 0);
if (senlen < 0)
{
perror("send:");
exit(0);
}
printf("(s)send success!\n");
close(socketFd);
return 0;
}
server
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#define SERVER_PORT 1234
int main(int argc, char *argv[])
{
char buf[20];
int socketFd, clientAddrLen, clientsocketFd;
struct sockaddr_in s_serverAddr;
struct sockaddr_in s_clientAddr;
socketFd = socket(AF_INET, SOCK_STREAM, 0);
if (socketFd < 0)
{
perror("socket:");
exit(-1);
}
printf("socket success!\n");
s_serverAddr.sin_family = AF_INET;
s_serverAddr.sin_port = htons(SERVER_PORT);
s_serverAddr.sin_addr.s_addr = htonl(INADDR_ANY);
if (bind(socketFd, (struct sockaddr *)&s_serverAddr, sizeof(s_serverAddr)) < 0)
{
perror("bind:");
exit(0);
}
printf("bind success!\n");
if (listen(socketFd, 10) < 0)
{
perror("listen:");
exit(0);
}
printf("listen success!\n");
clientsocketFd = accept(socketFd, (struct sockaddr *)&s_clientAddr, &clientAddrLen);
if (clientsocketFd < 0)
{
perror("accept:");
exit(0);
}
printf("accept success!\n");
int recvlen = recv(clientsocketFd, buf, 20, 0);
if (recvlen < 0)
{
perror("recv:");
exit(0);
}
printf("recv success!\n");
printf("recv(%d):%s \n", recvlen, buf);
close(socketFd);
close(clientsocketFd);
}
函数参考
套接字地址结构
字节序列转换
|