在C语言中就学过scanf和printf,其实理解socket就跟这两个输入输出差不多,只不过是信息的传输而已。
1.TCP服务器端(server)的默认函数调用顺序:
按照上述的调用顺序,我们可以来写个最简单的"hello world" server程序。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<arpa/inet.h>
#include<sys/socket.h> void error_handling(char* message); void error_handling(char* message) {
fputs(message, stderr);
fputc('\n', stderr);
exit();
} int main(int argc, char **argv)
{
int serv_sock;
int clnt_sock; //设置一个server地址serv_addr,client地址clnt_addr
struct sockaddr_in serv_addr;
struct sockaddr_in clnt_addr;
socklen_t clnt_addr_size = sizeof(clnt_addr); memset(&serv_addr, , sizeof(serv_addr));
memset(&serv_addr, , sizeof(serv_addr));
char message[] = "Hello world"; if (argc != ) {
printf("Usage : %s <port>\n", argv[]);
exit();
} //创建用于internet的流协议(TCP)socket
serv_sock = socket(PF_INET, SOCK_STREAM, );
if (serv_sock == -) {
error_handling("socket() error");
} serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
serv_addr.sin_port = htons(atoi(argv[])); //把socket和socket地址结构联系起来
if( bind(serv_sock,(struct sockaddr*)&serv_addr,sizeof(serv_addr)) == -) {
error_handling("bind() error");
} //server_socket用于监听
if ( listen(serv_sock, ) == -) {
error_handling("lisen() error");
} // 受理连接请求
clnt_sock = accept(serv_sock,(struct sockaddr*)&clnt_addr,&clnt_addr_size);
if ( clnt_sock == -) {
error_handling("accept() error");
} write(clnt_sock, message, sizeof(message));
close(clnt_sock);
close(serv_sock); return ;
}
2.与server端相对应的是客户端,其调用顺序为:
相对应的“hello world”client端程序就为:
hello_client.c
------
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<arpa/inet.h>
#include<sys/socket.h> void error_handling(char* message); void error_handling(char* message) {
fputs(message, stderr);
fputc('\n', stderr);
exit();
} int main(int argc, char **argv) {
int sock;
struct sockaddr_in serv_addr;
char message[];
int str_len;
memset(&serv_addr, , sizeof(serv_addr)); if (argc != )
{
printf("Usage: /%s <IP> <Port>\n",argv[]);
exit();
} //创建用于internet的流协议(TCP)socket
sock = socket(PF_INET, SOCK_STREAM, );
if (sock == -) {
error_handling("socket() error");
} //设置一个socket地址结构client_addr,代表客户机internet地址, 端口
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = inet_addr(argv[]);
serv_addr.sin_port = htons(atoi(argv[])); //把socket和socket地址结构联系起来
if( connect(sock,(struct sockaddr*)&serv_addr,sizeof(serv_addr)) == -) {
error_handling("connect() error");
} str_len = read(sock, message, sizeof(message) - );
if (str_len == -) {
error_handling("read() error");
} printf("Message from server : %s \n", message);
close(sock);
return ;
}
开始运行服务器端:
#gcc hello_server.c -o hserver
#./hserver
......开始挂起
开始运行客户端:
#gcc hello_client.c -o hclient
#./hclient 127.0.0.1
Message from server: Hello world