select收数据
之前写的服务器端 表示都无法收到client发的数据,找不到原因,原来是有个socket接收数据缓冲木有设置,现在设置后就可以正常收到数据啦!
server端:
#include <winsock.h>
#include <stdio.h> #include <string> #pragma comment(lib, "ws2_32.lib") #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 = ; i < BACKLOG; i++)
{
printf("[%d]:%d ", i, fd_A[i]);
}
printf("\n\n");
} int main(void)
{
WSADATA wsaData;
WSAStartup(0x0202, &wsaData);
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
int sin_size;
int yes = ;
char buf[BUF_SIZE];
int ret;
int i; if ((sock_fd = socket(AF_INET, SOCK_STREAM, )) == -) { perror("socket");
exit();
} //这一步很重要,不然数据可能收不到
int nRecvBuf = * ; //设置为32K
if (setsockopt(sock_fd,SOL_SOCKET,SO_RCVBUF,(const char*)&nRecvBuf,sizeof(int)) == -) {
perror("setsockopt");
exit();
} 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)) == -)
{
perror("bind");
exit();
} if (listen(sock_fd, BACKLOG) == -)
{
perror("listen");
exit();
} printf("listen port %d\n", MYPORT); fd_set fdsr;
int maxsock;
struct timeval tv;
conn_amount = ;
sin_size = sizeof(client_addr);
maxsock = sock_fd; while ()
{
FD_ZERO(&fdsr); FD_SET(sock_fd, &fdsr);
// timeout setting
tv.tv_sec = ;
tv.tv_usec = ;
// add active connection to fd set
for (i = ; i < BACKLOG; i++)
{
if (fd_A[i] != )
{
FD_SET(fd_A[i], &fdsr);
}
} ret = select(maxsock + , &fdsr, NULL, NULL, &tv);
if (ret < )
{
perror("select");
break; }
else if (ret == )
{
printf("timeout\n");
continue;
} // check every fd in the set
for (i = ; i < conn_amount; i++)
{
if(fd_A[i] > )
{
if (FD_ISSET(fd_A[i], &fdsr))
{
ret = recv(fd_A[i], buf, sizeof(buf), );
if (ret <= )
{ // client close
printf("client[%d] close\n", i);
--conn_amount;
closesocket(fd_A[i]);
FD_CLR(fd_A[i], &fdsr);
fd_A[i] = ;
}
else
{
if (ret < BUF_SIZE)
memset(&buf[ret], '\0', );
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 <= )
{
perror("accept");
continue;
}
// add to fd queue
if (conn_amount < BACKLOG)
{
for (int j = ; j < BACKLOG; ++j)
{
if (fd_A[j] == )
{
fd_A[j] = 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;
}
++conn_amount;
break;
}
}
}
else
{
printf("max connections arrive, exit\n");
send(new_fd, "bye", , );
closesocket(new_fd);
break;
}
}
}
// close other connections
for (i = ; i < BACKLOG; i++)
{
if (fd_A[i] != )
{
closesocket(fd_A[i]);
}
}
exit(); }
#include <stdio.h>
#include <WinSock2.h>
#pragma comment(lib, "ws2_32") #define MYPORT 1234 // the port users will be connecting to void CleanUpSocket( SOCKET clientSocket )
{
printf("SocketError:%d\n",WSAGetLastError());
closesocket(clientSocket);
WSACleanup();
} int BytesSum = ; int main()
{
int iResult;
WORD wVersionRequested;
WSADATA wsaData;
SOCKET clientSocket;
struct sockaddr_in clientService; wVersionRequested = MAKEWORD(, ); /* initialize windows socket */
iResult = WSAStartup(wVersionRequested, &wsaData);
if (iResult != )
{
printf("WSAStartup failed with error: %d\n", iResult);
return -;
}
else
{
printf("WSAStartup succeeded!\n");
} clientSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (clientSocket == INVALID_SOCKET)
{
printf("create socket failed with error: %d\n", WSAGetLastError());
WSACleanup();
return -;
}
else
{
printf("create socket(%d) succeeded!\n", clientSocket);
} clientService.sin_family = AF_INET;
clientService.sin_port = htons(MYPORT);
clientService.sin_addr.s_addr = inet_addr("127.0.0.1");
iResult = connect(clientSocket, (SOCKADDR *) &clientService, sizeof(clientService));
if (iResult == SOCKET_ERROR)
{
CleanUpSocket(clientSocket);
return -;
}
else
{
printf("connect succeed!\n");
} char lBuf[] = "Hello Kitty!";
int i = ;
char lrecvbyf[]; while(++i < )
{
int lResult = send(clientSocket, lBuf, strlen(lBuf)+,);
if (SOCKET_ERROR == lResult)
{
CleanUpSocket(clientSocket);
return ;
}
else
{
BytesSum += lResult;
printf("BytesSum(%d) Bytes Send:%d\n",BytesSum,lResult);
} //lResult = recv(clientSocket, lrecvbyf, strlen(lrecvbyf)+1,0);
//if (SOCKET_ERROR == lResult)
//{
// CleanUpSocket(clientSocket);
// return 0;
//}
//else
//{
// lrecvbyf[lResult] = '\0';
// printf("recv:%s\n",lrecvbyf);
// printf("BytesSum(%d) Bytes Send:%d\n",BytesSum,lResult);
//} } closesocket(clientSocket);
WSACleanup(); return ;
}
ok,继续努力,改进server端的缺点。
参考代码:http://www.cnblogs.com/faraway/archive/2009/03/06/1404449.html
select收数据的更多相关文章
- SQL Server游标 C# DataTable.Select() 筛选数据 什么是SQL游标? SQL Server数据类型转换方法 LinQ是什么? SQL Server 分页方法汇总
SQL Server游标 转载自:http://www.cnblogs.com/knowledgesea/p/3699851.html. 什么是游标 结果集,结果集就是select查询之后返回的所 ...
- C# DataTable.Select() 筛选数据
有时候我们需要对数据表进行筛选,微软为我们封装了一个公共方法, DataTable.Select(),其用法如下: Select() Select(string filterExpression) S ...
- MySql中利用insert into select 准备数据uuid主键冲突
MYSQL 中表1需要准备大量数据,内容主要取自表2,id必须为32位uuid (项目所有表都是这样,没办法), 准备这样插入: INSERT INTO TBL_ONE (ID, SOID, SNAM ...
- 利用select检索数据
没错这就是DQL,数据查询语言.来看看怎么用. select语句按照复杂程度来说分为简单查询.where查询.多表查询.子查询等. 先来看看select的语法 1.select 2.[distince ...
- select和select的数据渲染,你知道多少呢?
select和option是一对好兄弟,他们是一个很强大的组合.多个元素组合在一起才有的属性,他们两个加起来一切都有了. 所谓的面包也要,鲜花也要,就是这么的任性. 首先看看他们的基本html结构 当 ...
- Mysql命令下导出select查询数据之 select ... into outfile方法
Mysql日常使用中经常遇到将select查询的数据导出到本地目录的情况,以便数据备份.分析等. 接下来将介绍Mysql终端下使用 select ... into outfile 语句导出数据方法 命 ...
- 如何优化用SQL语句INSERT INTO … SELECT插入数据时锁全表的问题
1.binlog format 启用Row Based Replication(行复制)模式: SET GLOBAL binlog_format = 'ROW'; 如果你想永久的启用这个模式,请修改m ...
- TCP 服务端接收数据解析工具类
package com.ivchat.common.util; import java.io.BufferedReader;import java.io.IOException;import java ...
- Oracle的select检索数据
--Select语法 select [distinct | All] select_list from table_list [where_clause] [group_by_clause] [Hav ...
随机推荐
- 如何清空IFRAME中的HTML
window.frames["ifra"].document.write(""); window.frames["ifra"].docume ...
- SQL操作查漏补缺
SQL教程地址:http://www.w3school.com.cn/sql/index.asp TOP 子句 TOP 子句用于规定要返回的记录的数目. 对于拥有数千条记录的大型表来说,TOP 子句是 ...
- java 利用HttpURLConnection方式获取restful格式的服务数据
/** * @Author: * @Description:利用HttpURLConnection方式获取restful格式的服务数据 * @Date: */ private static List& ...
- Ubuntu通过 lshw 工具包查看物理网卡名称
步骤1:安装相关工具包 apt-get install lshw lshw-gtk 步骤2:执行lshw命令进行查看硬件信息
- MFC获得当前用户等信息
MFC获得当前用户等信息 #ifndef UNICODE #define UNICODE #endif #pragma comment(lib, "netapi32.lib") # ...
- VC++ MFC应用程序项目文件
<?xml version="1.0" encoding="utf-8"?> <Project DefaultTargets="Bu ...
- Android 模仿微信启动动画
本文内容 环境 项目结构 演示微信启动动画 本文演示微信启动动画.请点击此处下载,自行调试. 顺便抱怨一下,实践性(与研究性质的相对)技术博的"七宗罪": 第一宗罪,错字连篇,逻辑 ...
- AWR - Load Profile 节
AWR 报告的"Load profile"节,如下图所示,包含很多极为有用,却被经常忽视的信息.通常更倾向使用"instance efficiency percentag ...
- 线程:主线程、子线程 同步线程、异步线程 单线程、多线程 System.Threading与System.Windows.Threading
入门-------------------------------------------------------------------------------- 概述与概念 一个C#程序开始 ...
- Ubuntu MYSQL环境搭建
前期准备: 检查系统资源 内存大小 # grep MemTotal/proc/meminfo 检查系统版本 统一为: Ubuntu 12.04.1 LTS(GNU/Linux 3.2.0-29-gen ...