一、初级服务端代码,只实现了简单的连接和接收数据功能
#include<stdio.h>
#include<stdlib.h>#include<sys/socket.h>
#include<arpa/inet.h>
#include<sys/types.h>
#include<unistd.h>
#include<strings.h>
#include<string.h>
#define LISTEN_PORT 9999
int main(void )
{
int socket_fd,accept_fd;
struct sockaddr_in myserver;
struct sockaddr_in remote_addr;
if((socket_fd=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP))<0)
printf("socket() erro");
bzero(&myserver,sizeof(myserver));
myserver.sin_family=AF_INET;
myserver.sin_addr.s_addr=htonl(INADDR_ANY);
myserver.sin_port=htons(LISTEN_PORT);
if(bind(socket_fd,(struct sockaddr *)&myserver,sizeof(myserver))<0)
perror("bind() erro");
if(listen(socket_fd,20))
printf("listen() erro");
for(;;)
{
socklen_t sin_size=sizeof(struct sockaddr_in);
if((accept_fd=accept(socket_fd,(struct sockaddr*)&remote_addr,&sin_size))==-1)
{
printf("accept erro");
continue;
}
printf("received a connection from %s\n",(char *)inet_ntoa(remote_addr.sin_addr));
if(fork()==0)
{
char buffer[1024];
bzero(buffer,1024);
for(;;)
{
if((read(accept_fd,buffer,1024))<0)
{
printf("read() erro");
}
else
{
printf("recevied message:%s\n",buffer);
}
write(accept_fd,buffer,strlen(buffer)+1);
if(strcmp(buffer,"quit")==0)
{
close(accept_fd);
break;
}
bzero(buffer,1024);
}
exit(0);
}
}
return 0;
}
二、初级客户端代码,也只实现了简单的连接和发送数据功能
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define PORT 9999
#define SERVER_IP "127.0.0.1"
#define BUFFSIZE 256
int main()
{
int socket_fd;
struct sockaddr_in addr;
char buffer[BUFFSIZE];
if((socket_fd = socket(AF_INET,SOCK_STREAM,0))<0){
perror("socket");
exit(1);
}
bzero(&addr,sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port=htons(PORT);
addr.sin_addr.s_addr = inet_addr(SERVER_IP);
if(connect(socket_fd,(struct sockaddr *)&addr,sizeof(addr))<0){
perror("connect");
exit(1);
}
printf("client send message:\n");
for(;;){
bzero(buffer,BUFFSIZE);
int read_len=read(0,buffer,BUFFSIZE);
if(read_len>0)
{
write(socket_fd,buffer,read_len);
read_len=read(socket_fd,buffer,BUFFSIZE);
write(1,buffer,read_len);
}
}
return 0;
}