求c语言程序~ 题目:写一个服务器客户端模式的程序,要求服务器发送a,客户端收到A!

 我来答
匿名用户
2011-03-12
展开全部
/* File: server.c */

#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>

int main(int argc, char **argv)
{
int fd;
int address_len;
struct sockaddr_in address;

//建立套接口
fd = socket(AF_INET, SOCK_DGRAM, 0); //SOCK_DGRAM

//绑定地址和端口
bzero(&address, sizeof(address));
address.sin_family = AF_INET;
address.sin_addr.s_addr = htonl(INADDR_ANY);
address.sin_port = htons(1234);
address_len = sizeof(address);
bind(fd, (struct sockaddr *)&address, address_len);

while(1) {
struct sockaddr_in client_address;
socklen_t len = sizeof(client_address);
int n;
char line[80];

printf("waiting...");
fflush(stdout);

//接收数据
n = recvfrom(fd, line, 80, 0,
(struct sockaddr *)&client_address, &len);
printf("server received %d:%s", n, line);

//发送数据
sendto(fd, line, n, 0,
(struct sockaddr *)&client_address, len);
}
}

/* File: client.c */

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>

int main(int argc, char **argv)
{
int fd;
struct sockaddr_in address;
int address_len;
char line[80] = "Client to Server string!\n";
int n;

//建立套接口
fd = socket(AF_INET, SOCK_DGRAM, 0);//AF_INET和SOCK_DGRAM的组合对应UDP协议

//联接
bzero(&address, sizeof(address));
address.sin_family = AF_INET;
address.sin_addr.s_addr = inet_addr("193.193.196.1");
address.sin_port = htons(1234);
address_len = sizeof(address);

//发送数据
sendto(fd, line, strlen(line)+1, 0,
(struct sockaddr *)&address, sizeof(address));

//接收数据
n = recvfrom(fd, line, 80, 0, NULL, NULL);
printf("received %d:%s", n, line);
}

仔细读一下,最好下次能自己写^_^,起码要弄懂原理
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式