#include <stdioh>
#include <sys/typesh>
#include <sys/socketh>
#include <netinet/inh>
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));
addresssin_family = AF_INET;
addresssin_addrs_addr = htonl(INADDR_ANY);
addresssin_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: clientc /
#include <sys/typesh>
#include <sys/socketh>
#include <netinet/inh>
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));
addresssin_family = AF_INET;
addresssin_addrs_addr = inet_addr("1931931961");
addresssin_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);
}
仔细读一下,最好下次能自己写^_^,起码要弄懂原理socket
服务器给指定的客户端发消息该怎么处理(tcp)(c语言)
多个客户端之间进行通讯,通过服务器转发的形式,现在客户端1请求向客户端2发送消息,先把消息发送到服务器,服务器怎么才能把消息转发到客户端2而不是转发给客户端3或者他自己。代码我觉得是你自己写比较好。客户端很简单吧,只要简单的连接上服务器,然后将用户的输入发送到服务器就好,同时做下合法性检查就好了。服务器那边有个函数得解析表达式吧比如3467+21
得分开3467和+21先调一个函数求乘法,然后再用返回值做加法。解析表达式借鉴栈的思想。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)