Windows和Linux进行socket通信
作者:网络转载 发布时间:[ 2013/2/5 14:40:49 ] 推荐标签:
Linux侧的server代码,
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define HELLO_WORLD_SERVER_PORT 4000
#define LENGTH_OF_LISTEN_QUEUE 20
#define BUFFER_SIZE 1024
int main(int argc, char **argv)
{
struct sockaddr_in server_addr;
int server_socket;
int opt = 1;
bzero(&server_addr,sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = htons(INADDR_ANY);
server_addr.sin_port = htons(HELLO_WORLD_SERVER_PORT);
/* create a socket */
server_socket = socket(PF_INET,SOCK_STREAM,0);
if( server_socket < 0)
{
printf("Create Socket Failed!");
exit(1);
}
/* bind socket to a specified address*/
setsockopt(server_socket, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
if( bind(server_socket,(struct sockaddr*)&server_addr,sizeof(server_addr)))
{
printf("Server Bind Port : %d Failed!", HELLO_WORLD_SERVER_PORT);
exit(1);
}
/* listen a socket */
if(listen(server_socket, LENGTH_OF_LISTEN_QUEUE))
{
printf("Server Listen Failed!");
exit(1);
}
/* run server */
while (1)
{
struct sockaddr_in client_addr;
int client_socket;
socklen_t length;
char buffer[BUFFER_SIZE];
/* accept socket from client */
length = sizeof(client_addr);
client_socket = accept(server_socket, (struct sockaddr*)&client_addr, &length);
if( client_socket < 0)
{
printf("Server Accept Failed!
");
break;
}
/* receive data from client */
while(1)
{
bzero(buffer, BUFFER_SIZE);
length = recv(client_socket, buffer, BUFFER_SIZE, 0);
if (length < 0)
{
printf("Server Recieve Data Failed!
");
break;
}
if('q' == buffer[0])
{
printf("Quit from client!
");
break;
}
printf("%s
", buffer);
}
close(client_socket);
}
close(server_socket);
return 0;
}
Windows侧的代码使用vc6.0编译可以,而Linux侧的代码用gccok了,即gcc server.c -o server。首先,在linux侧输入./server,然后打开Widnows侧的client程序,然后在Windows侧的每一个字符输入都会在Linux打印出来。如果想退出,输入q即可。但是此时server不会退出,它在等待下一个client的通信,继续服务于大家,是这么简单。
这里的server和client代码是根据网友的代码修改而来,一并表示感谢。如有侵权,请邮件告知。
相关推荐
更新发布
功能测试和接口测试的区别
2023/3/23 14:23:39如何写好测试用例文档
2023/3/22 16:17:39常用的选择回归测试的方式有哪些?
2022/6/14 16:14:27测试流程中需要重点把关几个过程?
2021/10/18 15:37:44性能测试的七种方法
2021/9/17 15:19:29全链路压测优化思路
2021/9/14 15:42:25性能测试流程浅谈
2021/5/28 17:25:47常见的APP性能测试指标
2021/5/8 17:01:11