❶ 用C语言帮忙写一个“TCP Client/Server模式的通信程序设计与实现”
CLIENT:
#include <stdio.h>
#include <stdio.h>
#include <winsock.h>
#pragma comment(lib,"Ws2_32")
#define PORT 6666 /* 客户机连接远程主机的端口 */
#define MAXDATASIZE 100 /* 每次可以接收的最大字节 */
int main()
{
int sockfd, numbytes;
char buf[MAXDATASIZE];
char msg[MAXDATASIZE];
char *argv="127.0.0.1";
struct sockaddr_in their_addr; /* 对方的地址端口信息 */
WSADATA ws;WSAStartup(MAKEWORD(2,2),&ws); //初始化Windows Socket Dll
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
//如果建立socket失败,退出程序
printf("socket error\n");
exit(1);
}
//连接对方
their_addr.sin_family = AF_INET; /* 协议类型是INET */
their_addr.sin_port = htons(PORT); /* 连接对方PORT端口 */
their_addr.sin_addr.s_addr = inet_addr(argv); /* 连接对方的IP */
if (connect(sockfd, (struct sockaddr *)&their_addr,sizeof(struct sockaddr)) == -1)
{
//如果连接失败,退出程序
printf("connet error\n");
closesocket(sockfd);
exit(1);
}
while(1){
scanf("%s",msg);
//发送数据
if (send(sockfd, msg, MAXDATASIZE, 0) == -1)
{
printf("send error");
closesocket(sockfd);
exit(1);
}
//接收数据,并打印出来
if ((numbytes=recv(sockfd, buf, MAXDATASIZE, 0)) == -1)
{
//接收数据失败,退出程序
printf("recv error\n");
closesocket(sockfd);
exit(1);
}
buf[numbytes] = '\0';
printf("Received: %s\n",buf); }
closesocket(sockfd);
return 0;
}
SERVER:
#include <stdio.h>
#include <winsock.h>
#pragma comment(lib,"Ws2_32")
#define MYPORT 6666 /*定义用户连接端口*/
#define BACKLOG 10 /*多少等待连接控制*/ #define MAXDATASIZE 100
int main()
{
int sockfd, new_fd; /*定义套接字*/
struct sockaddr_in my_addr; /*本地地址信息 */
struct sockaddr_in their_addr; /*连接者地址信息*/
int sin_size,numbytes; char msg[10],buf[MAXDATASIZE];
WSADATA ws;
WSAStartup(MAKEWORD(2,2),&ws); //初始化Windows Socket Dll
//建立socket
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
//如果建立socket失败,退出程序
printf("socket error\n");
exit(1);
}
//bind本机的MYPORT端口
my_addr.sin_family = AF_INET; /* 协议类型是INET */
my_addr.sin_port = htons(MYPORT); /* 绑定MYPORT端口*/
my_addr.sin_addr.s_addr = INADDR_ANY; /* 本机IP*/
if (bind(sockfd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr))== -1)
{
//bind失败,退出程序
printf("bind error\n");
closesocket(sockfd);
exit(1);
}
//listen,监听端口
if (listen(sockfd, BACKLOG) == -1)
{
//listen失败,退出程序
printf("listen error\n");
closesocket(sockfd);
exit(1);
}
printf("listen...");
//等待客户端连接
sin_size = sizeof(struct sockaddr_in);
if ((new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size)) == -1)
{
printf("accept error\n");
closesocket(sockfd);
exit(1);
}
printf("\naccept!\n");
while(1) {
if((numbytes=recv(new_fd, buf, MAXDATASIZE, 0)) == -1) continue;
if(!strcmp(buf,"bye"))
{
//成功,关闭套接字
closesocket(sockfd);
closesocket(new_fd);
return 0;
}
printf("%s %d",buf,strlen(buf));
sprintf(msg,"%d",strlen(buf));
if (send(new_fd,msg,MAXDATASIZE, 0) == -1)
{
printf("send ERRO");
closesocket(sockfd);
closesocket(new_fd);
return 0;
}
}
}