最近2天一直在研究怎么写UDP形式的socket,今天让我给弄出来了,哈哈。
以下是简单的c/s程序:
server.c
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define PORT 8999
#define MAXSIZE 4096
int main(int argc, char *argv[])
{
int sockfd, addr_len;
struct sockaddr_in serv_addr, clnt_addr;
char recvmsg[MAXSIZE], sendmsg[MAXSIZE];
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd < 0) {
perror("socket error");
return -1;
}
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(PORT);
serv_addr.sin_addr.s_addr = INADDR_ANY;
bzero(&(serv_addr.sin_zero), 8);
if (bind(sockfd, (struct sockaddr *)&serv_addr, sizeof(struct sockaddr)) < 0) {
perror("bind err");
return -1;
}
while(1) {
memset(sendmsg, 0, MAXSIZE);
memset(recvmsg, 0, MAXSIZE);
addr_len = sizeof(struct sockaddr);
/* 所谓的非阻塞I/O */
if (recvfrom(sockfd, recvmsg, MAXSIZE, 0, (struct sockaddr *)&clnt_addr, &addr_len) < 0) {
perror("recv");
continue;
}
printf("begin to accept\n");
printf("recv from %s : %s\n", inet_ntoa(clnt_addr.sin_addr), recvmsg);
strcpy(sendmsg, "who are you ?? Let me cc!");
sendto(sockfd, sendmsg, strlen(sendmsg) + 1, 0, (struct sockaddr *)&clnt_addr, addr_len);
}
return 0;
}
client.c
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define PORT 8999
#define DESIP "192.168.23.109"
#define MAXSIZE 4096
int main(int argc, char *argv[])
{
int sockfd, addr_len;
struct sockaddr_in des_addr;
char sendmsg[MAXSIZE], recvmsg[MAXSIZE];
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd < 0) {
perror("socket error");
return -1;
}
des_addr.sin_family = AF_INET;
des_addr.sin_port = htons(PORT);
des_addr.sin_addr.s_addr = inet_addr(DESIP);
bzero(&(des_addr.sin_zero), 8);
while (1) {
memset(recvmsg, 0, MAXSIZE);
memset(sendmsg, 0, MAXSIZE);
printf("input:\n");
gets(sendmsg);
if (strcmp(sendmsg, "quit") == 0) {
close(sockfd);
printf("close connection\n");
return -1;
}
if (sendto(sockfd, sendmsg, strlen(sendmsg) + 1, 0, (struct sockaddr *)&des_addr, sizeof(struct sockaddr)) < 0) {
perror("sendto");
continue;
}
printf("send ok...\n");
while (1) {/* 所谓的非阻塞I/O */
addr_len = sizeof(struct sockaddr);
if (recvfrom(sockfd, recvmsg, MAXSIZE, 0, (struct sockaddr *)&des_addr, &addr_len) < 0) {
continue;
}
printf("recv from %s : %s\n", inet_ntoa(des_addr.sin_addr), recvmsg);
break;
}
}
return 0;
}
贴出代码供初学的人参考,以少走弯路,记得大学里我也曾经又过一段时间准备研究这个socket,但是最终还是由于种种原因而夭折,当然,也有网络上提供的可以运行的实例代码太少的一个影响。呵呵,贴上来也有便于自己以后偶尔查查。
阅读(8726) | 评论(1) | 转发(0) |