/*************************************************************************
> File Name: MySever.c
> Author: xuchen_allen
> Mail: xuchen_allen@163.com
> Created Time: 2019年02月09日 星期六 10时12分14秒
************************************************************************/
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<string.h>
#include<sys/types.h>
#include<strings.h>
#include<ctype.h>
#include<arpa/inet.h>
#define _PORT_ 6666
#define _IP_ADDR_ "192.168.1.108"
int main(void)
{
int sfd,cfd;
int len,i;
char buf[1024],clie_IP[128];
//定义一个套接字:
struct sockaddr_in ser_addr,clie_addr;
socklen_t clie_addr_len;
sfd = socket(AF_INET,SOCK_STREAM,0); //指定期望的网络协议类型;
if(sfd<0){
perror("socket fail");
exit(1);
}
else{
printf("socket success\n");
}
//指定协议族,ip地址,端口地址;
bzero(&ser_addr,sizeof(ser_addr)); //对socket_in 进行初始化
ser_addr.sin_family = AF_INET;
ser_addr.sin_addr.s_addr = htonl(INADDR_ANY);
ser_addr.sin_port = htons(_PORT_);
//将上述的地址与套接字绑定:
if((bind(sfd,(struct sockaddr*)&ser_addr,sizeof(ser_addr)))<0){
perror("bind fail");
exit(1);
}
else{
printf("bind success\n");
}
//开始监听:
if((listen(sfd,2))<0){
perror("listen fail");
exit(1);
}
else{
printf("listen success\n");
}
//等待客户端连接:
printf("waitting for client connect ...\n");
//接受客户端的模块:
for(;;){
socklen_t clie_addr_len = sizeof(clie_addr);
if((cfd=accept(sfd,(struct sockaddr *)&clie_addr,&clie_addr_len))<0){
perror("accept fail");
exit(1);
}
else{
printf("client IP:%s\tPort:%d\n",inet_ntop(AF_INET,&clie_addr.sin_addr.s_addr,clie_IP,sizeof(clie_IP))\
,ntohs(clie_addr.sin_port));
}
while(1){
len = read(cfd,buf,sizeof(buf));
if(len<0){
perror("read fail");
exit(1);
}
else{
printf("client:%s\n",buf);
}
if(write(STDOUT_FILENO,buf,len)<0){
perror("write fail");
exit(1);
}
for(i=0;i<len;i++)
buf[i]=toupper(buf[i]);
if(write(cfd,buf,len)<0){
perror("write fail");
exit(1);
}
}
}
close(sfd);
close(cfd);
return 0;
}
#include<stdio.h>
#include<unistd.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<string.h>
#include<errno.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<stdlib.h>
#define _SEVER_IP_ "192.168.1.108"
#define _PORT_ 6666
int main()
{
int sfd,len;
struct sockaddr_in serv_addr;
char buf[1024];
sfd = socket(AF_INET,SOCK_STREAM,0);
if(sfd<0){
perror("socket fail");
exit(1);
}
else{
printf("client socket success\n");
}
bzero(&serv_addr,sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
inet_pton(AF_INET,_SEVER_IP_,&serv_addr.sin_addr.s_addr);
serv_addr.sin_port = htons(_PORT_);
if(connect(sfd,(struct sockaddr*)&serv_addr,sizeof(serv_addr))<0){
perror("client conect fail");
exit(1);
}
else{
printf("client connect success\n");
}
while(1){
fgets(buf,sizeof(buf),stdin);
int r = write(sfd,buf,strlen(buf));
if(r<0){
perror("client write fail");
exit(1);
}
printf("write=============== %d\n",r);
len = read(sfd,buf,sizeof(buf));
printf("Read len ======== %d\n",len);
if(write(STDOUT_FILENO,buf,len)<0){
perror("client write fail");
exit(1);
}
}
close(sfd);
return 0;
}
服务器和客户端分开在两台电脑上进行了测试,完美运行