先來一個基本能使用的版本:
server端代碼:
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <netinet/in.h>
#include <arpa/inet.h>
const int MYPORT = 1240;
const int BACKLOG = 5;
const int BUF_SIZE = 1024;
using namespace std;
int main()
{
int sock_fd,new_fd;
struct sockaddr_in server_addr,client_addr;
char buf[BUF_SIZE];
if((sock_fd = socket(AF_INET,SOCK_STREAM,0)) == -1)
{
perror("socket");
exit(1);
}
int yes = 1;//yes = 1;(即TRUE)
if (setsockopt(sock_fd, SOL_SOCKET, SO_REUSEADDR, &yes,sizeof(yes)) == -1)
{
perror("setsockopt");
exit(1);
}
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(MYPORT);
server_addr.sin_addr.s_addr = INADDR_ANY;
memset(server_addr.sin_zero,'0',sizeof(server_addr.sin_zero));
if (bind(sock_fd, (struct sockaddr * )&server_addr, sizeof(server_addr)) == -1)
{
perror("bind");
exit(1);
}
if (listen(sock_fd, BACKLOG) == -1)
{
perror("listen");
exit(1);
}
fd_set fdsr;
int maxsock;
int i;
struct timeval tv;
int fd_A[BACKLOG];//fd
int con_amount = 0;//
int ret;
maxsock = sock_fd;
//int sin_size = sizeof(client_addr);//int len ; wrong
socklen_t sin_size = sizeof(client_addr);
while (1)
{
//select函數(shù)會清空它所檢測的socket描述符集合恶阴,導(dǎo)致每次調(diào)用select()之前都必須把socket描述符重新加入到待檢測的集合中
FD_ZERO(&fdsr);
FD_SET(sock_fd, &fdsr);
tv.tv_sec = 30;//每一次查詢 套接字是否就緒的時間
tv.tv_usec = 0;
//for(i = 0;i<BACKLOG;i++) //BACKLOG --段錯誤 吐核
for (i = 0; i < con_amount; i++)
{
if (fd_A[i] != 0)
FD_SET(fd_A[i],&fdsr);
}
ret = select(maxsock + 1, &fdsr, NULL, NULL, &tv);//
if (ret < 0)
{
perror("select");
break;
}
else if (ret == 0)// 沒有準(zhǔn)備就緒的文件描述符 就進(jìn)入下一次循環(huán)
{
cout << "timeout" << endl;
continue;
}
//有準(zhǔn)備就緒的套接字溶浴,則分別檢查哪些 連接套接字 和 監(jiān)聽套接字 已經(jīng)就緒 分別進(jìn)行數(shù)據(jù)讀取和建立連接
for (i = 0; i < con_amount; i++)
{
if (FD_ISSET(fd_A[i], &fdsr))
{
ret = recv(fd_A[i], buf, BUF_SIZE - 1, 0);
if (ret > 0)
{
buf[ret] = '\0';
cout << "msg from " << fd_A[i] << "is: " << buf << endl;
}
else//------------------client close
{
cout << "client " << fd_A[i] << " is closed!" << endl;
close(fd_A[i]);
//FD_CLR(fd_A[i],&fdsr);
fd_A[i] = 0;
/*
perro("recv");
exit(1);
*/
}
}
}//end of "for"
// 以下說明異常有來自客戶端的連接請求
if (FD_ISSET(sock_fd, &fdsr))
{
//if((new_fd = accept(sock_fd,(struct sockaddr *)&client_addr,sizeof(client_addr)) == -1)//error
if ((new_fd = accept(sock_fd, (struct sockaddr *)&client_addr, &sin_size)) == -1)
{
perror("accept");
exit(1);
}
//
if (con_amount < BACKLOG)
{
fd_A[con_amount++] = new_fd;
//FD_SET(new_fd,&fdsr); // no need , fd_A[i] != 0 will be added to fdsr in the begin of each loop
cout << "new client:" <<inet_ntoa(client_addr.sin_addr) << ":" << ntohs(client_addr.sin_port) << endl;
//update maxsock ------
if (new_fd > maxsock)
maxsock = new_fd;
}
else
{//send msg
cout << "Max connections arrived!" << endl;
send(new_fd, "Bye", 4, 0);
close(new_fd);
//break;//
}
}
}//end of "while(1)"
/*
close(sock_fd);
for(i = 0;i<con_amount;i++)
{
if(fd_A[i] != 0)
close(fd_A[i]);
}
*/
return 0;
}
客戶端代碼:
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
/* 服務(wù)器程序監(jiān)聽的端口號 */
//#define PORT 1240
/* 我們一次所能夠接收的最大字節(jié)數(shù) */
#define MAXDATASIZE 100
int main(int argc, char *argv[])
{
/* 套接字描述符 */
int sockfd, numbytes;
char buf[MAXDATASIZE];
int port;
struct hostent *he;
/* 連接者的主機(jī)信息 */
struct sockaddr_in their_addr;
/* 檢查參數(shù)信息 */
if (argc != 3)
{
/* 如果沒有參數(shù)布疙,則給出使用方法后退出 */
fprintf(stderr,"usage: server_host server_port\n");
exit(1);
}
/* 取得主機(jī)信息 */
if ((he = gethostbyname(argv[1])) == NULL)
{
/* 如果 gethostbyname()發(fā)生錯誤,則顯示錯誤信息并退出 */
herror("gethostbyname");
exit(1);
}
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
/* 如果 socket()調(diào)用出現(xiàn)錯誤則顯示錯誤信息并退出 */
perror("socket");
exit(1);
}
port = atoi(argv[2]);//
/* 主機(jī)字節(jié)順序 */
their_addr.sin_family = AF_INET;
/* 網(wǎng)絡(luò)字節(jié)順序,短整型 */
their_addr.sin_port = htons(port);
their_addr.sin_addr = *((struct in_addr *)he->h_addr);
/* 將結(jié)構(gòu)剩下的部分清零*/
bzero(&(their_addr.sin_zero), 8);
if (connect(sockfd, (struct sockaddr *)&their_addr, sizeof(struct sockaddr)) == -1)
{
/* 如果 connect()建立連接錯誤,則顯示出錯誤信息,退出 */
perror("connect");
exit(1);
}
/*
if((numbytes=recv(sockfd, buf, MAXDATASIZE, 0)) == -1)
{
// 如果接收數(shù)據(jù)錯誤绎巨,則顯示錯誤信息并退出
perror("recv");
exit(1);
}
buf[numbytes] = '\0';
printf("Received: %s",buf);
bzero(buf,100);*/
strcpy(buf,"Received your message!\n");
send(sockfd, buf, strlen(buf), 0);
/*
sleep(100);
strcpy(buf,"Received your message2!\n");
send(sockfd,buf,strlen(buf),0);
*/
//close(sockfd);
return 0;
}
以上內(nèi)容引自:https://blog.csdn.net/hishentan/article/details/38308053
下面是完善一些的版本:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define MYPORT 1234 // the port users will be connecting to
#define BACKLOG 5 // how many pending connections queue will hold
#define BUF_SIZE 200
int fd_A[BACKLOG]; // accepted connection fd
int conn_amount; // current connection amount
void showclient()
{
int i;
printf("client amount: %d\n", conn_amount);
for (i = 0; i < BACKLOG; i++) {
printf("[%d]:%d ", i, fd_A[i]);
}
printf("\n\n");
}
int main(void)
{
int sock_fd, new_fd; // listen on sock_fd, new connection on new_fd
struct sockaddr_in server_addr; // server address information
struct sockaddr_in client_addr; // connector's address information
socklen_t sin_size;
int yes = 1;
char buf[BUF_SIZE];
int ret;
int i;
if ((sock_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror("socket");
exit(1);
}
if (setsockopt(sock_fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) {
perror("setsockopt");
exit(1);
}
server_addr.sin_family = AF_INET; // host byte order
server_addr.sin_port = htons(MYPORT); // short, network byte order
server_addr.sin_addr.s_addr = INADDR_ANY; // automatically fill with my IP
memset(server_addr.sin_zero, '\0', sizeof(server_addr.sin_zero));
if (bind(sock_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1) {
perror("bind");
exit(1);
}
if (listen(sock_fd, BACKLOG) == -1) {
perror("listen");
exit(1);
}
printf("listen port %d\n", MYPORT);
fd_set fdsr;
int maxsock;
struct timeval tv;
conn_amount = 0;
sin_size = sizeof(client_addr);
maxsock = sock_fd;
while (1) {
// initialize file descriptor set
FD_ZERO(&fdsr);
FD_SET(sock_fd, &fdsr);
// timeout setting
tv.tv_sec = 30;
tv.tv_usec = 0;
// add active connection to fd set
for (i = 0; i < BACKLOG; i++) {
if (fd_A[i] != 0) {
FD_SET(fd_A[i], &fdsr);
}
}
ret = select(maxsock + 1, &fdsr, NULL, NULL, &tv);
if (ret < 0) {
perror("select");
break;
} else if (ret == 0) {
printf("timeout\n");
continue;
}
// check every fd in the set
for (i = 0; i < conn_amount; i++) {
if (FD_ISSET(fd_A[i], &fdsr)) {
ret = recv(fd_A[i], buf, sizeof(buf), 0);
if (ret <= 0) { // client close
printf("client[%d] close\n", i);
close(fd_A[i]);
FD_CLR(fd_A[i], &fdsr);
fd_A[i] = 0;
} else { // receive data
if (ret < BUF_SIZE)
memset(&buf[ret], '\0', 1);
printf("client[%d] send:%s\n", i, buf);
}
}
}
// check whether a new connection comes
if (FD_ISSET(sock_fd, &fdsr)) {
new_fd = accept(sock_fd, (struct sockaddr *)&client_addr, &sin_size);
if (new_fd <= 0) {
perror("accept");
continue;
}
// add to fd queue
if (conn_amount < BACKLOG) {
fd_A[conn_amount++] = new_fd;
printf("new connection client[%d] %s:%d\n", conn_amount,
inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port));
if (new_fd > maxsock)
maxsock = new_fd;
} else {
printf("max connections arrive, exit\n");
send(new_fd, "bye", 4, 0);
close(new_fd);
break;
}
}
showclient();
}
// close other connections
for (i = 0; i < BACKLOG; i++) {
if (fd_A[i] != 0) {
close(fd_A[i]);
}
}
exit(0);
}
繼續(xù)優(yōu)化后的版本:
void run()
{
char msg[BUF_SIZE];
int Listen_socket,ret,on;
struct sockaddr_in local_addr;
struct sockaddr_in client_addr;
int i;
fd_set fdsr; //文件描述符集的定義
socklen_t addr_size;
addr_size = sizeof(struct sockaddr_in);
int conn_amount = 0; //當(dāng)前最大活躍連接數(shù)
int new_fd;
struct timeval tv;
//建立socket套接字
if( (Listen_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == -1)
{
emit err_msg_signal("failed create socket");
}
//bind API 函數(shù)將允許地址的立即重用
on = 1;
ret = setsockopt( Listen_socket, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on) );
int nNetTimeout=2000;//2秒
//設(shè)置發(fā)送時限
setsockopt(Listen_socket,SOL_SOCKET,SO_SNDTIMEO,(char *)&nNetTimeout,sizeof(int) );
//設(shè)置接收時限
setsockopt(Listen_socket,SOL_SOCKET,SO_RCVTIMEO,(char *)&nNetTimeout,sizeof(int));
//設(shè)置本機(jī)服務(wù)類型
local_addr.sin_family = AF_INET;
local_addr.sin_port = htons(port);
local_addr.sin_addr.s_addr = INADDR_ANY;
//while(flag_port == 0)
//綁定本機(jī)IP和端口號
if(bind(Listen_socket, (struct sockaddr*)&local_addr, sizeof(struct sockaddr)) == -1)
{
emit err_msg_signal("failed bind");
}
//監(jiān)聽客戶端連接
if(listen(Listen_socket, 8) == -1)
{
emit err_msg_signal("failed listen");
}
QTime current_time;
current_time = QTime::currentTime();
int flag_minutechange = 0,lastminute = current_time.currentTime().minute();
int maxsock = Listen_socket;
/***************************************
以下為并發(fā)連接處理,系統(tǒng)關(guān)鍵部分
***************************************/
while (1)
{
if( current_time.currentTime().minute() != lastminute) //每次循環(huán)開始都讀取系統(tǒng)時間蠕啄,與上次分鐘數(shù)比較场勤,為以下超時判斷提供依據(jù)
{
lastminute = current_time.currentTime().minute();
flag_minutechange = 1;
}
FD_ZERO(&fdsr); //每次進(jìn)入循環(huán)都重建描述符集
FD_SET(Listen_socket, &fdsr);
for (i = 0; i < MAXCLIENT; i++) //將存在的套接字加入描述符集
{
if (fd[i] != 0)
{
FD_SET(fd[i], &fdsr);
if (flag_minutechange == 1)
{
con_time[i]--;
if (con_time[i] <= 0)
{
close(fd[i]);
FD_CLR(fd[i], &fdsr);
fd[i] = 0;
conn_amount--;
}
}
}
}
flag_minutechange = 0;
tv.tv_sec = 1;
tv.tv_usec = 0;
ret = select(maxsock + 1, &fdsr, NULL, NULL,&tv); //關(guān)鍵的select()函數(shù),用來探測各套接字的異常
//如果在文件描述符集中有連接請求或發(fā)送請求歼跟,會作相應(yīng)處理和媳,
//從而成功的解決了單線程情況下阻塞進(jìn)程的情況,實現(xiàn)多用戶連接與通信
if (ret < 0) //<0表示探測失敗
{
qDebug()<<"failed select\n";
break;
}
else if (ret == 0) //=0表示超時哈街,下一輪循環(huán)
{
//qDebug()<<"timeout\n";
continue;
}
// 如果select發(fā)現(xiàn)有異常留瞳,循環(huán)判斷各活躍連接是否有數(shù)據(jù)到來
for (i = 0; i < conn_amount; i++)
{
if (FD_ISSET(fd[i], &fdsr))
{
ret = recv(fd[i], msg, BUF_SIZE, 0);
if (ret <= 0) // recv<=0,表明客戶端關(guān)閉連接,服務(wù)器也關(guān)閉相應(yīng)連接骚秦,并把連接套接子從文件描述符集中清除
{
qDebug("client[%d] close\n", i);
close(fd[i]);
FD_CLR(fd[i], &fdsr);
fd[i] = 0;
conn_amount--;
}
else //否則表明客戶端有數(shù)據(jù)發(fā)送過來她倘,作相應(yīng)接受處理
{
con_time[i] = MAX_IDLECONNCTIME; //重新寫入fd[i]的超時數(shù),再此之后如果MAX_IDLECONNCTIME分鐘內(nèi)此連接無反應(yīng)作箍,服務(wù)器會關(guān)閉該連接
if (ret < BUF_SIZE)
emit err_msg_signal("client ip: " + QString::fromLatin1(inet_ntoa(client_addr.sin_addr)) +
" port: " + QString::number(ntohs(client_addr.sin_port))+" coming data");
qDebug("client[%d] send:%s\n", i, msg);
msg[ret] = '\0';
emit recv_msg_signal(QString::fromLatin1(msg),fd[i]);
//send(fd[i],msg,ret,0);
}
}
}
// 以下說明異常有來自客戶端的連接請求
if (FD_ISSET(Listen_socket, &fdsr))
{
new_fd = accept(Listen_socket, (struct sockaddr *)&client_addr, &addr_size);
if (new_fd <= 0)
{
qDebug("failed accept");
continue;
}
// 判斷活躍連接數(shù)時候是否小于最大連接數(shù)硬梁,如果是,添加新連接到文件描述符集中
if (conn_amount < MAXCLIENT)
{
for(i = 0;i < MAXCLIENT;i++)
{
if(fd[i] == 0)
{
fd[i] = new_fd;
con_time[i] = MAX_IDLECONNCTIME; //每次新建立連接胞得,設(shè)置該連接的超時數(shù)荧止,如果此連接此后MAX_IDLECONNCTIME分鐘內(nèi)無反應(yīng),關(guān)閉該連接
break;
}
}
conn_amount++;
//fd[conn_amount++] = new_fd;
qDebug("new connection client[%d] %s:%d\n", conn_amount,
inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port));
emit err_msg_signal("client ip: " + QString::fromLatin1(inet_ntoa(client_addr.sin_addr)) +
" port: " + QString::number(ntohs(client_addr.sin_port)));
if (new_fd > maxsock)
maxsock = new_fd;
}
else
{
qDebug("MAXCLIENT arrive, exit\n");
send(new_fd, "over MAXCLIENT\n", 25, 0);
close(new_fd);
continue;
}
}
}
}
以上內(nèi)容引自:
https://www.cnblogs.com/faraway/archive/2009/03/06/1404449.html