1楼:匿名用户
用一个线程监听端口,没一个请求都用单独的一个线程处理,以多线程方式执行就可以了。如果是单线程模式,肯定是有阻塞的。
采用tcp协议,使用socket编程,编写程序完成客户端发送消息给服务端,服务端接到消息后,再发
2楼:树大没风
服务端**:
/*server.c*/
#include
#include
#include
#include
#include
#include
#include
#include
#define port 4321
#define buffer_size 1024
#define max_que_conn_nm 5
int main()
printf("socket id = %d\n",sockfd);
/*设置sockaddr_in 结构体中相关参数*/
server_sockaddr.sin_family = af_inet;
server_sockaddr.sin_port = htons(port);
server_sockaddr.sin_addr.s_addr = inaddr_any;
bzero(&(server_sockaddr.sin_zero), 8);
int i = 1;/* 使得重复使用本地地址与套接字进行绑定 */
setsockopt(sockfd, sol_socket, so_reuseaddr, &i, sizeof(i));
/*绑定函数bind*/
if (bind(sockfd, (struct sockaddr *)&server_sockaddr, sizeof(struct sockaddr))== -1)
printf("bind success!\n");
/*调用listen函数*/
if (listen(sockfd, max_que_conn_nm) == -1)
printf("listening....\n");
/*调用accept函数,等待客户端的连接*/
if ((client_fd = accept(sockfd, (struct sockaddr *)&client_sockaddr, &sin_size)) == -1)
/*调用recv函数接收客户端的请求*/
memset(buf , 0, sizeof(buf));
if ((recvbytes = recv(client_fd, buf, buffer_size, 0)) == -1)
printf("received a message: %s\n", buf);
if ((sendbytes = send(sockfd, buf, strlen(buf), 0)) == -1)
close(sockfd);
exit(0);
} 客户端:
/*client.c*/
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define port 4321
#define buffer_size 1024
int main(int argc, char *argv)
/*地址解析函数*/
if ((host = gethostbyname(argv[1])) == null)
memset(buf, 0, sizeof(buf));
sprintf(buf, "%s", argv[2]);
/*创建socket*/
if ((sockfd = socket(af_inet,sock_stream,0)) == -1)
/*设置sockaddr_in 结构体中相关参数*/
serv_addr.sin_family = af_inet;
serv_addr.sin_port = htons(port);
serv_addr.sin_addr = *((struct in_addr *)host->h_addr);
bzero(&(serv_addr.sin_zero), 8);
/*调用connect函数主动发起对服务器端的连接*/
if(connect(sockfd,(struct sockaddr *)&serv_addr, sizeof(struct sockaddr))== -1)
/*发送消息给服务器端*/
if ((sendbytes = send(sockfd, buf, strlen(buf), 0)) == -1)
if ((recvbytes = recv(sockfd, buf, buffer_size, 0)) == -1)
close(sockfd);
exit(0);}
java问题用socket编写客户端程序
1楼 匿名用户 给你一个我写的示例,用的是基于tcp的socket技术,你锻炼一下,改一改,不会改再找我! 客户端 import java socket import java io inputstream import java io outputstream import java io inp...