在写基于TCP服务器端的时候,主要分为 以下几步来完成
1.创建套接字
2.将本地地址与一套接口绑定
3.创建一个套接口并监听申请的连接
4.在一个套接口接受一个连接
server.c
#include<stdio.h>
#include<sys/types.h>#include<sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include<stdlib.h>
#include<string.h>
static void Usage(const char *proc)
{
printf("Usage:%s [local_ip] [local_port]\n",proc);
}
int startup(const char* ip,int port) //创建套接字
{
int sock = socket(AF_INET,SOCK_STREAM,0);
if(sock<0)
{
perror("socket");
exit(2);
}
struct sockaddr_in local;
local.sin_family=AF_INET;
local.sin_port = htons(port);
local.sin_addr.s_addr = inet_addr(ip);
if(bind(sock,(struct sockaddr*)&local,sizeof(local))<0) //绑定
{
perror("bind");
exit(3);
}
if(listen(sock,10)<0) //监听
{
perror("listen");
exit(4);
}
return sock;
}
int main(int argc,char* argv[])
{
if(argc!=3)
{
Usage(argv[0]);
return 1;
}
int listen_sock = startup(argv[1],atoi(argv[2]));
char buf[1024];
while(1)
{
struct sockaddr_in remote;
socklen_t len = sizeof(remote);
int new_sock = accept(listen_sock,(struct sockaddr*)&remote,&len);
if(new_sock<0)
{
perror("accept");
continue;
}
while(1)
{
char buf[1024];
ssize_t s = read(new_sock,buf,sizeof(buf)-1);
if(s>0)
{
buf[s]=0;
printf("Client say#%s\n",buf);
write(new_sock,buf,strlen(buf));
}
else
{
close(new_sock);
}
}
}
return 0 ;
}
客户端分为以下几步完成
Client.c
1.创建套接字和服务器一样
2.建立与指定socket的连接
#include<stdlib.h>
#include<sys/socket.h>
#include <netinet/in.h>
#include<syspes.h>
#include<arpa/inet.h>
#include<string.h>
static void usage(const char* proc)
{
printf("Usage:%s [local_ip] [local_port]\n",proc);
}
//tcp_client server_ip server_port
int main(int argc,char* argv[])
{
if(argc!=3)
{
usage(argv[0]);
return 1;
}
int sock = socket(AF_INET,SOCK_STREAM,0);
if(sock < 0 )
{
perror("socket");
exit(2);
}
struct sockaddr_in server_sock;
server_sock.sin_family = AF_INET;
server_sock.sin_port = htons(atoi(argv[2]));
server_sock.sin_addr.s_addr = inet_addr(argv[1]);
if(connect(sock,(struct sockaddr*)&server_sock,sizeof(server_sock))<0) //连接
{
printf("connect failed ");
exit(3);
}
printf("connect success\n");
char buf[1024];
while(1)
{
printf("Please Enter#");
fflush(stdout);
ssize_t s=read(0,buf,sizeof(buf)-1);
if(s>0)
{
buf[s-1]=0;
write(sock,buf,strlen(buf));
s = read(sock,buf,sizeof(buf)-1);
if(s>0)
{
buf[s] = 0;
printf("server ehco:%s\n ",buf);
}
}
}
}