linux下用socket实现服务器与客户端通信,高手进来帮忙看看!!急求!!
多看书阿...
用select或者poll或者epoll吧..还有一个类似的
功能就是,等待事件发生,比如某个socket(或者句柄)有了数据什么的,select可以判断出来,并且返回,让你知道哪个socket出现事情了。他监听的句柄范围中没事情发生时,进程或者线程就阻塞(超时时间可以设置).
这样你就可以在select知道哪个出现数据之后,再去操作对应的socket
你说相互通信,干吗还要中转,自己用ip:port就好了阿...
要是大家都对服务器有某个请求,服务器端就用select吧..如果你处理的链接数很大,就用poll或者epoll吧,效果更好....剩下的自己去查资料...
C语言socket编程怎么实现2个客户端之间通信
网络的Socket数据传输是一种特殊的I/O,Socket也是一种文件描述符。Socket也具有一个类似于打开文件的函数调用Socket(),该函数返回一个整型的Socket描述符,随后的连接建立、数据传输等操作都是通过该Socket实现的。下面用Socket实现一个windows下的c语言socket通信例子,这里我们客户端传递一个字符串,服务器端进行接收。【服务器端】#include "stdafx.h"#include #include #include #define SERVER_PORT 5208 //侦听端口void main(){ WORD wVersionRequested; WSADATA wsaData; int ret, nLeft, length; SOCKET sListen, sServer; //侦听套接字,连接套接字 struct sockaddr_in saServer, saClient; //地址信息 char *ptr;//用于遍历信息的指针 //WinSock初始化 wVersionRequested=MAKEWORD(2, 2); //希望使用的WinSock DLL 的版本 ret=WSAStartup(wVersionRequested, &wsaData); if(ret!=0) { printf("WSAStartup() failed!\n"); return; } //创建Socket,使用TCP协议 sListen=socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (sListen == INVALID_SOCKET) { WSACleanup(); printf("socket() faild!\n"); return; } //构建本地地址信息 saServer.sin_family = AF_INET; //地址家族 saServer.sin_port = htons(SERVER_PORT); //注意转化为网络字节序 saServer.sin_addr.S_un.S_addr = htonl(INADDR_ANY); //使用INADDR_ANY 指示任意地址 //绑定 ret = bind(sListen, (struct sockaddr *)&saServer, sizeof(saServer)); if (ret == SOCKET_ERROR) { printf("bind() faild! code:%d\n", WSAGetLastError()); closesocket(sListen); //关闭套接字 WSACleanup(); return; } //侦听连接请求 ret = listen(sListen, 5); if (ret == SOCKET_ERROR) { printf("listen() faild! code:%d\n", WSAGetLastError()); closesocket(sListen); //关闭套接字 return; } printf("Waiting for client connecting!\n"); printf("Tips: Ctrl+c to quit!\n"); //阻塞等待接受客户端连接 while(1)//循环监听客户端,永远不停止,所以,在本项目中,我们没有心跳包。 { length = sizeof(saClient); sServer = accept(sListen, (struct sockaddr *)&saClient, &length); if (sServer == INVALID_SOCKET) { printf("accept() faild! code:%d\n", WSAGetLastError()); closesocket(sListen); //关闭套接字 WSACleanup(); return; } char receiveMessage[5000]; nLeft = sizeof(receiveMessage); ptr = (char *)&receiveMessage; while(nLeft>0) { //接收数据 ret = recv(sServer, ptr, 5000, 0); if (ret == SOCKET_ERROR) { printf("recv() failed!\n"); return; } if (ret == 0) //客户端已经关闭连接 { printf("Client has closed the connection\n"); break; } nLeft -= ret; ptr += ret; } printf("receive message:%s\n", receiveMessage);//打印我们接收到的消息。 } // closesocket(sListen); // closesocket(sServer); // WSACleanup();}【客户端】#include "stdafx.h"#include #include #include #define SERVER_PORT 5208 //侦听端口void main(){ WORD wVersionRequested; WSADATA wsaData; int ret; SOCKET sClient; //连接套接字 struct sockaddr_in saServer; //地址信息 char *ptr; BOOL fSuccess = TRUE; //WinSock初始化 wVersionRequested = MAKEWORD(2, 2); //希望使用的WinSock DLL的版本 ret = WSAStartup(wVersionRequested, &wsaData); if(ret!=0) { printf("WSAStartup() failed!\n"); return; } //确认WinSock DLL支持版本2.2 if(LOBYTE(wsaData.wVersion)!=2 || HIBYTE(wsaData.wVersion)!=2) { WSACleanup(); printf("Invalid WinSock version!\n"); return; } //创建Socket,使用TCP协议 sClient = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (sClient == INVALID_SOCKET) { WSACleanup(); printf("socket() failed!\n"); return; } //构建服务器地址信息 saServer.sin_family = AF_INET; //地址家族 saServer.sin_port = htons(SERVER_PORT); //注意转化为网络节序 saServer.sin_addr.S_un.S_addr = inet_addr("192.168.1.127"); //连接服务器 ret = connect(sClient, (struct sockaddr *)&saServer, sizeof(saServer)); if (ret == SOCKET_ERROR) { printf("connect() failed!\n"); closesocket(sClient); //关闭套接字 WSACleanup(); return; } char sendMessage[]="hello this is client message!"; ret = send (sClient, (char *)&sendMessage, sizeof(sendMessage), 0); if (ret == SOCKET_ERROR) { printf("send() failed!\n"); } else printf("client info has been sent!"); closesocket(sClient); //关闭套接字 WSACleanup();}
linux网络编程中阻塞和非阻塞socket的区别
阻塞socket和非阻塞socket的区别:
1、读操作
对于阻塞的socket,当socket的接收缓冲区中没有数据时,read调用会一直阻塞住,直到有数据到来才返回。当socket缓冲区中的数据量小于期望读取的数据量时,返回实际读取的字节数。当sockt的接收缓冲区中的数据大于期望读取的字节数时,读取期望读取的字节数,返回实际读取的长度。
对于非阻塞socket而言,socket的接收缓冲区中有没有数据,read调用都会立刻返回。接收缓冲区中有数据时,与阻塞socket有数据的情况是一样的,如果接收缓冲区中没有数据,则返回错误号为EWOULDBLOCK,表示该操作本来应该阻塞的,但是由于本socket为非阻塞的socket,因此立刻返回,遇到这样的情况,可以在下次接着去尝试读取。如果返回值是其它负值,则表明读取错误。
因此,非阻塞的rea调用一般这样写:
if ((nread = read(sock_fd, buffer, len)) < 0)
{
if (errno == EWOULDBLOCK)
{
return 0; //表示没有读到数据
}else return -1; //表示读取失败
}else return nread;读到数据长度
2、写操作
对于写操作write,原理是类似的,非阻塞socket在发送缓冲区没有空间时会直接返回错误号EWOULDBLOCK,表示没有空间可写数据,如果错误号是别的值,则表明发送失败。如果发送缓冲区中有足够空间或者是不足以拷贝所有待发送数据的空间的话,则拷贝前面N个能够容纳的数据,返回实际拷贝的字节数。
而对于阻塞Socket而言,如果发送缓冲区没有空间或者空间不足的话,write操作会直接阻塞住,如果有足够空间,则拷贝所有数据到发送缓冲区,然后返回.
非阻塞的write操作一般写法是:
int write_pos = 0;
int nLeft = nLen;
while (nLeft > 0)
{
int nWrite = 0;
if ((nWrite = write(sock_fd, data + write_pos, nLeft)) <= 0)
{
if (errno == EWOULDBLOCK)
{
nWrite = 0;
}else return -1; //表示写失败
}
nLeft -= nWrite;
write_pos += nWrite;
}
return nLen;
3、建立连接
阻塞方式下,connect首先发送SYN请求道服务器,当客户端收到服务器返回的SYN的确认时,则connect返回.否则的话一直阻塞.
非阻塞方式,connect将启用TCP协议的三次握手,但是connect函数并不等待连接建立好才返回,而是立即返回。返回的错误码为EINPROGRESS,表示正在进行某种过程.
4、接收连接
对于阻塞方式的倾听socket,accept在连接队列中没有建立好的连接时将阻塞,直到有可用的连接,才返回。
非阻塞倾听socket,在有没有连接时都立即返回,没有连接时,返回的错误码为EWOULDBLOCK,表示本来应该阻塞。
无阻塞的设置方法
方法一:fcntl
int flag;
if (flag = fcntl(fd, F_GETFL, 0) <0) perror("get flag");
flag |= O_NONBLOCK;
if (fcntl(fd, F_SETFL, flag) < 0)
perror("set flag");
方法二:ioctl
int b_on = 1;
ioctl (fd, FIONBIO, &b_on);
socket编程中connect()函数链接问题
直接用就好了嘛~~
1.简单服务器
//#include
//#pragma comment(lib,"WS2_32.lib")
WSADATA wsd;
static UINT port=%%1;
UINT Listen(LPVOID pParam)
{
SOCKET sServer,sClient;
char buf[1024];
int retVal;
if(WSAStartup(MAKEWORD(2,2),&wsd)!=0)
{
return -1;//失败
}
sServer=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if(INVALID_SOCKET==sServer)
{
WSACleanup();
return -1;//创建套接字失败
}
SOCKADDR_IN addrServ;
addrServ.sin_family=AF_INET;
addrServ.sin_port=htons((short)pParam);
addrServ.sin_addr.s_addr=INADDR_ANY;
retVal=bind(sServer,(LPSOCKADDR)&addrServ,sizeof(SOCKADDR_IN));
if(SOCKET_ERROR==retVal)
{
closesocket(sServer);
WSACleanup();
return -1;//绑定套接字失败
}
retVal=listen(sServer,1);
if(SOCKET_ERROR==retVal)
{
closesocket(sServer);
WSACleanup();
return -1;//开始监听失败
}
sockaddr_in addrClient;
int addrClientlen=sizeof(addrClient);
sClient=accept(sServer,(sockaddr FAR*)&addrClient,&addrClientlen);
if(INVALID_SOCKET==sClient)
{
closesocket(sServer);
WSACleanup();
return -1;//开始接受客户端连接失败
}
ZeroMemory(buf,sizeof(buf));
retVal=recv(sClient,buf,sizeof(buf),0);
if(SOCKET_ERROR==retVal)
{
closesocket(sServer);
closesocket(sClient);
WSACleanup();
return -1;//接收数据失败
}
CString %%2(buf);
closesocket(sServer);
closesocket(sClient);
WSACleanup();
return 0;
}
CWinThread *pThread=AfxBeginThread(Listen,&port);
2.简单客户端
//#include
//#pragma comment(lib,"WS2_32.lib")
WSADATA wsd;
SOCKET sHost;
SOCKADDR_IN servAddr;
char buf[1024];
int retVal;
if(WSAStartup(MAKEWORD(2,2),&wsd)!=0)
{
return -1;//失败
}
sHost=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if(INVALID_SOCKET==sHost)
{
WSACleanup();
return -1;//创建套接字失败
}
servAddr.sin_family=AF_INET;
servAddr.sin_addr.s_addr=inet_addr(%%3);
servAddr.sin_port=htons((short)%%2);
int nServAddlen=sizeof(servAddr);
retVal=connect(sHost,(LPSOCKADDR)&servAddr,sizeof(servAddr));
if(SOCKET_ERROR==retVal) {
closesocket(sHost);
WSACleanup();
return -1;//连接服务器失败
}
ZeroMemory(buf,sizeof(buf));
strcpy(buf,%%3);
retVal=send(sHost,buf,sizeof(buf),0);
if(SOCKET_ERROR==retVal)
{
closesocket(sHost);
WSACleanup();
return -1;//向服务器发送数据失败
}
closesocket(sHost);
WSACleanup();
3.获得本机IP
//#include
//#pragma comment(lib,"WS2_32.lib")
WSADATA wsd;
if(WSAStartup(MAKEWORD(2,2),&wsd)!=0)
{
return -1;//失败
}
char szHostname[100],szHostaddress[200];
if(gethostname(szHostname,sizeof(szHostname))!=SOCKET_ERROR)
{
HOSTENT *pHostEnt=gethostbyname(szHostname);
if(pHostEnt!=NULL){
sprintf(szHostaddress,"%d.%d.%d.%d",
( pHostEnt->h_addr_list[0][0]&0x00ff ),
( pHostEnt->h_addr_list[0][1]&0x00ff ),
( pHostEnt->h_addr_list[0][2]&0x00ff ),
( pHostEnt->h_addr_list[0][3]&0x00ff ));
}
}
else
return;
CString %%1(szHostaddress);
5.点对点通信
//#include
//#pragma comment(lib,"WS2_32.lib")
WSADATA wsd;
SOCKADDR_IN addrServ,addrServ2;
SOCKET sServer,sClient,sHost;
int retVal;
sockaddr_in addrClient;
char buf[1024];
static UINT port=%%2;
BOOL listenerRun=TRUE;
UINT Listen(LPVOID pParam)
{
addrServ.sin_family=AF_INET;
addrServ.sin_port=htons((UINT)pParam);
addrServ.sin_addr.s_addr=INADDR_ANY;
retVal=bind(sServer,(LPSOCKADDR)&addrServ,sizeof(SOCKADDR_IN));
if(SOCKET_ERROR==retVal)
{
closesocket(sServer);
WSACleanup();
return -1;//绑定套接字失败
}
retVal=listen(sServer,1);
if(SOCKET_ERROR==retVal)
{
closesocket(sServer);
WSACleanup();
return -1;//开始监听失败
}
int addrClientlen=sizeof(addrClient);
sClient=accept(sServer,(sockaddr FAR*)&addrClient,&addClientlen);
if(INVALID_SOCKET==sClient)
{
closesocket(sServer);
WSACleanup();
return -1;//接收客户端请求失败
}
while(listenerRun)
{
ZeroMemory(buf,sizeof(buf));
retVal=recv(sClient,buf,sizeof(buf));
if(SOCKET_ERROR==retVal)
{
closesocket(sServer);
closesocket(sClient);
WSACleanup();
return -1;//接收客户端数据失败
}
CString %%4(buf);
}
}
if(WSAStartup(MAKEWORD(2,2),&wsd)!=0)
{
return -1;//失败
}
sServer=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if(INVALID_SOCKET==sServer)
{
WSACleanup();
return -1;//创建套接字失败
}
CWinThread *pThread=AfxBeginThread(Listen,&port);
sHost=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if(INVALID_SOCKET==sHost)
{
WSACleanup();
return -1;//创建套接字失败
}
servAddr2.sin_family=AF_INET;
servAddr2.sin_addr.s_addr=inet_addr(%%1);
servAddr.sin_port=htons((short)%%3);
int nServerAddrlen=sizeof(servAddr2);
retVal=connect(sHost,(LPSOCKADDR)&servAddr2,sizeof(servAddr2));
if(SOCKET_ERROR==retVal)
{
closesocket(sHost);
WSACleanup();
return -1;//连接失败
}
zeroMemory(buf,sizeof(buf));
strcpy(buf,%%5);
retVal=send(sHost,buf,sizeof(buf),0);
if(SOCKET_ERROR==retVal)
{
closesocket(sHost);
WSACleanup();
return -1;//向发送数据失败
}
listenerRun=FALSE;
DWORD dwExitCode;
::GetExitCodeThread(pThread->m_hThread,&dwExitCode);
pThread=null;
closesocket(sServer);
closesocket(sClient);
closesocket(sHost);
WSACleanup();
Linux下C语言socket编程
socket编程一般是基于tcp或者udp协议来写的,你的问题很抽象,我不知道你要的是基于tcp还是udp的socket编译。我把相对难的基于tcp协议的socket编译给你吧。你想看懂我的代码需要知道tcp的三次握手机制。否则我写了注释,你看代码也有点困难。 ////服务端的代码
1 #include
2 #include
3 #include
4 #include
5 #include
6 #include
7 #include
8 #include
9
10 #define LOCAL_PORT 1234
11 #define MAX_LEN 512
12 #define MAX_NUM 5
13
14 int main(int argc, char *argv[])
15 {
16 int sock_fd, sock_data;
17 int ret, len_addr;
18 char buf[MAX_LEN];
19 ssize_t len;
20 struct sockaddr_in local_addr, remote_addr;
21
22 sock_fd = socket(AF_INET, SOCK_STREAM, 0); //创建套接字,sock_fd是套接字描述符,类似我们的身份证号码
23 if (sock_fd < 0)
24 {
25 perror("socket()");
26 return sock_fd;
27 }
28
29 local_addr.sin_family = AF_INET;// 协议族,ipv4
30 local_addr.sin_port = htons(LOCAL_PORT);// 把服务器端口转换成网络字节序
31 local_addr.sin_addr.s_addr = inet_addr("127.0.0.1");//把字符串形式的ip转换成网络字节序
32
33 ret = bind(sock_fd, (struct sockaddr *)&local_addr, (size_t)sizeof(local_addr));// 把sock_fd和本机ip,端口邦定
34 if (ret < 0)
35 {
36 perror("bind()");
37 close(sock_fd);
38 return ret;
39 }
40
41 ret = listen(sock_fd, MAX_NUM);//监听socket
42 if (ret)
43 {
44 perror("listen()");
45 close(sock_fd);
46 return ret;
47 }
48
49 memset(buf, 0, MAX_LEN);
50
51 len_addr = sizeof(remote_addr);
52
53 sock_data = accept(sock_fd, (struct sockaddr *)&remote_addr, (socklen_t *)&len_addr);//接受客户端的连接
54 if (ret < 0)
55 {
56 perror("accept()");
57 close(sock_fd);
58 return ret;
59 }
60
61 while (1)
62 {
63 int slen;
64 len = recv(sock_data, buf, MAX_LEN, 0);//接受客户端的数据
65 if (len < 0)
66 {
67 perror("recv()");
68 close(sock_data);
69 close(sock_fd);
70 return len;
71 }
72 printf("%s\n", buf);
73
74 slen = send(sock_data, "congratulation!", 15, 0);//向客户端发送数据
75 if (slen <= 0)
76 {
77 printf("slen = %d\n", slen);
78 perror("send()");
79 close(sock_data);
80 close(sock_fd);
81 return slen;
82 }
83 sleep(1);
84 }
85
86 close(sock_data);
87 close(sock_fd);
88
89 return 0;
90 }
////////////客户端的代码 1 #include
2 #include
3 #include
4 #include
5 #include
6 #include
7 #include
8 #include
9
10 #define REMOTE_PORT 1234
11 #define MAX_LEN 512
12
13 int main(int argc, char *argv[])
14 {
15 int sock_fd, ret;
16 int len;
17 char buf[MAX_LEN];
18 struct sockaddr_in local_addr, remote_addr;
19
20 sock_fd = socket(AF_INET, SOCK_STREAM, 0);
21 if (sock_fd < 0)
22 {
23 perror("socket()");
24 return sock_fd;
25 }
26
28 local_addr.sin_family = AF_INET;
29 local_addr.sin_addr.s_addr = htonl(INADDR_ANY); //自动获取本机的ip地址
30 local_addr.sin_port = htons(0); //随机选取可用的端口,并不是指定端口为0
31
33 remote_addr.sin_family= AF_INET;
34 remote_addr.sin_port = htons(REMOTE_PORT);
35 ret = inet_aton("127.0.0.1", &remote_addr.sin_addr);
36
38 ret = bind(sock_fd, (struct sockaddr *)&local_addr, sizeof(local_addr)); //把本机的ip,port和socket绑定
39 if (ret < 0)
40 {
41 perror("bind() !");
42 close(sock_fd);
43 return ret;
44 }
45
47 ret = connect(sock_fd, (struct sockaddr *)&remote_addr, (socklen_t)sizeof(remote_addr)); //把本机的socket和对方的port,ip建立连接
48 if (ret < 0)
49 {
50 perror("connect()");
51 close(sock_fd);
52 return ret;
53 }
54
55 memset(buf, 0, MAX_LEN);
56
57 while (1)
58 {
59 int i;
60 // len = send(sock_fd, buf, (size_t)MAX_LEN, 0);
61 len = send(sock_fd, "hello", 6, 0);
62 if (len <= 0)
63 {
64 perror("send()");
65 close(sock_fd);
66 return ret;
67 }
68
69 // printf("%d-->bytes send!\n", len);
70 sleep(1);
71
72 len = recv(sock_fd, buf, MAX_LEN, 0);
73 if (len <= 0)
74 {
75 perror("recv()");
76 close(sock_fd);
77 return ret;
78 }
79
80 for (i = 0; i < len; i++)
81 {
82 printf("%c", buf[i]);
83 }
84 printf("\n");
85 }
86
87 close(sock_fd);
88
89 return 0;
90 }
你把服务端和客户端这两个程序分别保存为server.c和client.c。然后编译gcc server.c -o server,gcc client .c -o client。运行时先运行服务端,用命令./server,再运行客户端,用命令./client。 注意运行命令是“点 斜杠”,“点”表示当前目录。
linux C语言编程,socket实现的即使通讯系统
Socket通信创建步骤:(1)通过socket()函数创建socket(2)通过bind函数绑定socket于设备地址(3)进行读写操作read/recv/recvfrom write/send/sendto(4)close方法关闭套接字例子如下:test1.c#include #include #include #include #include int main(void) { //create socket int fd = socket(AF_INET, SOCK_DGRAM, 0); if(fd==-1) { perror("socket\n"); exit(-1); } printf("socket fd=%d\n",fd); //build connection address struct sockaddr_in addr; addr.sin_family = AF_INET; addr.sin_port = htons(6666); addr.sin_addr.s_addr = inet_addr("127.0.0.1"); int r; r = bind(fd,(struct sockaddr*)&addr,sizeof(addr)); if(r==-1) { perror("bind"); close(fd); exit(-1); } printf("bind address successful!\n"); //accept or send message char buf[255]; struct sockaddr_in from; socklen_t len; len = sizeof(from); while(1) { r = recvfrom(fd,buf,sizeof(buf)-1,0,(struct sockaddr*)&from,&len); if(r>0) { buf[r]=0; printf("The message from %s is:%s\n",inet_ntoa(from.sin_addr),buf); } else { break; } } //close socket close(fd); return 0; }test2.c#include #include #include #include #include #include #include int main(void) { //create socket int fd = socket(AF_INET,SOCK_DGRAM,0); if(fd==-1) { perror("socket"); exit(-1); } printf("create socket OK!\n"); //create an send address struct sockaddr_in addr={}; addr.sin_family = AF_INET; addr.sin_port = htons(6666); addr.sin_addr.s_addr=inet_addr("127.0.0.1"); //send the message to the specify address int r; char buf[255]; while(1) { r = read(0,buf,sizeof(buf)-1); if(r<=0) break; sendto(fd,buf,r,0,(struct sockaddr*)&addr,sizeof(addr)); } //close socket close(fd); return 0; }先运行test1.c,然后运行test2.c,在test2.c运行后输入内容,在test1.c所在终端中就会显示信息运行结果如下: