C++ socket 客户端recv不到数据 5C

#include
#include /* for socket() and bind() /
#include /
for printf() and fprintf() /
#include /
for sockaddr_in and inet_ntoa() /
#include /
for close() /
#include /
for memset() /
#include /
for atoi() */

#include "Msg.h"
#include "queue"
#include "pack.h"
#include "analysis.h"
///////////////

using namespace std;
#define MYPORT 7000
#define SERVER_IP "127.0.0.1"

#define BUFFER_SIZE 1024
int sock_cli;//client文件描述符

void* recvMess(void* ptr) {
unsigned char recvbuf[BUFFER_SIZE];
while (1){
memset(recvbuf,0x00, sizeof(recvbuf));
cout<<"ready recv"<<endl;
int len = recv(sock_cli,recvbuf, sizeof(recvbuf),0);
if(len == -1){
cout << " client -1 recv error" << endl;
} else if (len == 0){
cout << "clent 0 recv over" << endl;
} else {
cout << len << endl;
}
}

int main()
{

///定义sockfd
//sock_cli = socket(AF_INET,SOCK_STREAM,0);
sock_cli = socket(AF_INET,SOCK_STREAM ,IPPROTO_TCP);
if(sock_cli <0){
    cout << "socket creatation failed!" << endl;
    return -1;
}
///定义sockaddr_in
struct sockaddr_in servaddr;
memset(&servaddr, 0, sizeof(servaddr));

servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(MYPORT);  ///服务器端口
servaddr.sin_addr.s_addr = inet_addr(SERVER_IP);  ///服务器ip

if (connect(sock_cli, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0)
{
    perror("connect");
    exit(1);
}

pthread_t recv_szMessage_thread;
int  recv_szMessage_thread_flag = pthread_create(& recv_szMessage_thread,NULL,recvMess,NULL);
if ( recv_szMessage_thread_flag !=0){
    cout<< "client create recv thread failed"<<endl;
}
pthread_detach( recv_szMessage_thread);

while(1){
}
close(sock_cli);
return 0;

}

3个回答

qq_39588327
qq_39588327 我 memset过啊, 打断点 每次到recv这就沉了
10 个月之前 回复

当我把 服务端关闭时,就会recv的返回值是0

这种代码网上多得是,你咋出的错呢,是不是服务器那边就没弄好,导致客户端没收到数据?

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
[紧急求助]socket客户端recv不到数据问题
最近在做telnet连接AP的动态库。发现connect()后无法正常recv()数据(无法接收到login:这一句),很郁闷。然后就翻阅网上的例子,也没发现什么好的方法。以下是实际情况,请各位大人帮我想想怎么搞。rn接收代码:rnrn[code=C/C++]rn int ret = 0;rn fd_set allset, rset;rn int countStr = 0;rnrn FD_ZERO(&allset);rn FD_SET(CientSocket, &allset);rnrn rset = allset;rn ret = ::select(CientSocket + 1, &rset, NULL, NULL, NULL);rn if(ret > 0)rn rn countStr = ::recv(CientSocket, string, sizeof(string), 0);rn rn[/code]rnrncmd实际输出:rn-------------------------------rn-----Welcome to ATP Cli------rn-------------------------------rnLogin: rootrnPassword:rnATP>shrnrnrnBusyBox vv1.9.1 (2011-12-17 14:20:04 CST) built-in shell (ash)rnEnter 'help' for a list of built-in commands.rnrn#rn
recv接收不到数据!!
while(1)rn rn byte_count = recv(sock, buf, sizeof(buf), 0);rn if(byte_count>0)rn rn return 1;rn rn elsern rn continue;rn rn rn 这样都接收不到数据。郁闷中................
C socket read不到数据
我在用C编写一个服务器端和客户端用来发送文件,但是read不到数据,我sleep三秒之后又能接收到数据了,这是为什么啊
多次send,recv不到数据
sp.bh=gbh;rn sp.pw=SRC_PW;rn sp.sizeofhx=sizeof(DWORD)*3;rn sp.taskbz=SRC_SCR_NUM;rn sp.threadbz=SOCKET_SCR_THREAD;rn WriteErrorLog("开始发送块数");rn if (!SendSRCPacket(&sp,mysock))rn rn WriteErrorLog("发送数据块数包失败");rn return 0;rn rn rn send(mysock,(char*)&dfsize,4,0);rn send(mysock,(char*)&dwDIBSize,4,0);rn send(mysock,(char*)&dComlen,4,0);rnrn sp.bh=gbh;rn sp.pw=SRC_PW;rn sp.sizeofhx=sizeof(BITMAPFILEHEADER);rn sp.taskbz=SRC_SCR_BMPHDR;rn sp.threadbz=SOCKET_SCR_THREAD;rn if (!SendSRCPacket(&sp,mysock))rn rn WriteErrorLog("发送数据块数包失败2");rn return 0;rn rn rn if (SOCKET_ERROR==send(mysock,(char*)&bmfHdr,sp.sizeofhx,0))rn rn WriteErrorLog("发送文件头失败");rn return 0;rn rn rn /*sp.bh=gbh;rn sp.pw=SRC_PW;rn sp.sizeofhx=sizeof(BITMAPINFOHEADER);rn sp.taskbz=SRC_SCR_BMPHDR;rn sp.threadbz=SOCKET_SCR_THREAD;rn SendSRCPacket(&sp,mysock);rn send(mysock,(char*)&bi,sp.sizeofhx,0);*/rn rn DWORD dpy=0;rn int count=0;rn char debuginfo[50];rn sprintf_s(debuginfo,"欲发送长度%d,分包数%d",dComlen,dfsize);rn WriteErrorLog(debuginfo);rn while (dpy+0x400<=dComlen)rn rn //Sleep(500);rn sp.bh=gbh;rn sp.pw=SRC_PW;rn sp.sizeofhx=0x400;rn sp.taskbz=SRC_SCR_DATA;rn sp.threadbz=SOCKET_SCR_THREAD;rn SendSRCPacket(&sp,mysock);rn /*if (SOCKET_ERROR==send(mysock,(char*)((BYTE*)pmem+dpy),sp.sizeofhx,0))rn rn WriteErrorLog("发送分块文件失败");rn return 0;rn */rn SRCCheckSend(mysock,(char*)((BYTE*)pmem+dpy),sp.sizeofhx);//函数中用select模型判断了下socket是否可写rn rn rn rn dpy+=0x400;rn count++;rn char errbuf[30];rn sprintf_s(errbuf,"发送第%d个包",count);rn WriteErrorLog(errbuf);rn rn rn if (dComlen-dpy>0)//还有数据没有发送rn rn sp.bh=gbh;rn sp.pw=SRC_PW;rn sp.sizeofhx=dComlen-dpy;rn sp.taskbz=SRC_SCR_DATA;rn sp.threadbz=SOCKET_SCR_THREAD;rn SendSRCPacket(&sp,mysock);rn send(mysock,(char*)((BYTE*)pmem+dpy),sp.sizeofhx,0);rn count++;rn rn sp.bh=gbh;rn sp.pw=SRC_PW;rn sp.sizeofhx=0;rn sp.taskbz=SRC_SCR_OVER;rn sp.threadbz=SOCKET_SCR_THREAD;rn SendSRCPacket(&sp,mysock);rn上面的代码是我程序中用来发送屏幕数据的,我一台服务器上安装程序后发现客户端根本无法收到数据(同样的程序在虚拟机可以收到数据) 还有最奇怪的一点是 我在每次发送之前加上Sleep(500)之后 客户端程序又可以接收到来自服务器的数据 rn不过这样做的后果大家都清楚 求高手急救下 到底是怎么回事?
linux c socket recv问题
send成功了,recv时候报:rnrecieve error!: Connection reset by peerrnrn有什么抓包工具可用的,推荐一下,谢谢。
socket 通信接收不到数据 我是用recv()接收的
server 端rn#includern#includern#includernusing namespace std;rnint main()rnrn int clientlen;rn struct sockaddr_in clientaddr;rn struct hostent *hp;rn char chInfo[64];rn char *haddrp;rn char buffer[5];rn int length;rn WSADATA wsaData;rn WORD a=MAKEWORD(2,3);rn int ret = WSAStartup(MAKEWORD(9,9), &wsaData);rn if (ret != 0)rn rn cout<<"Error"<h_name<<"("<rn#includern#includern#include rnusing namespace std;rnint main()rnrnrn struct hostent *hp;rn int length;rn char buffer[5];rn struct in_addr addr;rn struct sockaddr_in serveraddr;rn WSADATA wsaData;rn int ret = WSAStartup(MAKEWORD(2,2), &wsaData);rn if (ret != 0)rn rn cout<<"Error"<h_addr,hp->h_length);rnrn serveraddr.sin_family = hp->h_addrtype;rn serveraddr.sin_port = htons(6000);rn if(connect(clientfd, (struct sockaddr *)&serveraddr, sizeof(serveraddr))<0)rn cout<<"error"<
socket 受不到数据
我bind一个端口,用WSAEventSelect 机制去监控端口数据的收发,但是遇到一个问题就是无法收到数据。rn用Network Sniffer监控端口时却可以看到有数据发送到该端口,但就是没有触发FD_Read事件,有人能告诉我是什么原因吗?
多线程 socket不到数据
小弟遇到的问题如下:rn发送文件时类似三次握手方式,先是客户端发送数据,等待服务器响应,(如果时单线程的话则recv函数一直等待,可以接收服务器数据),但是采用多线程时,子线程recv函数因为等待时间片的原因,服务器发送的数据失败,如果在recv函数处加断点调试的话,就可以正常接收。如何在子线程中实现接收到服务器的响应报文?rn先谢谢各位大虾了!
求助!!! socket send的数据和recv的数据不一致???
老师叫我们做远程控制软件, Server端用MFC, Client端用WIN32(Server端和Client端都使用SDK里的socket);rn用Cilent端远程控制Server端;rnrn我做到文件传输的时候,socket第三次recv时数据总是和send出来的不对;rn经过观察发现,在16进制下接受到数据前都多了fd,如我发送100(16进制:64) 接收到的是2万多(16进制:64fd);rnrn我用线程接收,接收的过程有几次函数调用,case while(1)等语句;rnrn我找了一天也没找到问题,这是怎么回事呀?????
为什么 recv函数接收不到数据? 高分!
if(connect(fd,(struct sockaddr*)&server,sizeof(struct sockaddr))==INVALID_SOCKET)rn rn closesocket(fd);rn return "00000";rn rn ioctlsocket(fd,FIONBIO,(unsigned long*)&argp); //设置非阻塞模式rn int sendResult = send(fd,t,sendLen,0); //向server端发送一个消息rn int intsize;rn intsize=t.GetLength();rn if(sendResult==SOCKET_ERROR)rn rn closesocket(fd);rn return ;rn rnrn char recvBuf[64];rn memset(recvBuf,0,64);rnrn int recvResult = recv(fd,recvBuf,64,0); //为何接收不到数据?rnrn我做的是client,我向 server 端发送一个消息后,Server端回立刻给client回执一个消息,而client为什么recv不到数据?
怎么RECV不到?
void CAnotherSrvDlg::OnBnClickedButton1()rnrn // TODO: 在此添加控件通知处理程序代码rn if (StartFlag != 0 )rn return ;rn StartFlag = 1;rn WSADATA wsaData;rn int err;rn rn rn err = WSAStartup(0x101,&wsaData);rn if (err != 0)rn rn ::MessageBox(NULL,_T("WSAStartup Error"),_T("WSAStartup Error"),MB_OK);rn return ;rn rn if (LOBYTE (wsaData.wVersion)!= 1 || HIBYTE (wsaData.wVersion)!= 1 )rn rn ::MessageBox(NULL,_T("wsaversion error"),_T("WSAStartup Error"),MB_OK);rn WSACleanup();rn return ;rn rn SOCKET m_sockSrv = socket(AF_INET,SOCK_STREAM,0);rn SOCKADDR_IN addrSrv;rn addrSrv.sin_addr.S_un.S_addr = htonl(INADDR_ANY);rn addrSrv.sin_family = AF_INET;rn addrSrv.sin_port = htons(6122);rn bind (m_sockSrv,(SOCKADDR*)&addrSrv,sizeof(SOCKADDR));rn if(listen(m_sockSrv,5) == SOCKET_ERROR)rn rn ::MessageBox(NULL,_T("listen failed"),_T(""),MB_OK);rn return ;rn rn SOCKADDR_IN addrClient;rn int len = sizeof (SOCKADDR);rn SOCKET sockConn = accept(m_sockSrv,(SOCKADDR*)&addrClient,&len);rn if(sockConn == INVALID_SOCKET)rn rn ::MessageBox(NULL,_T("accept failed"),_T(""),MB_OK);rn DWORD dwError = WSAGetLastError();rn closesocket(sockConn);rn return ; rn rn char * recvBuf = "";rn recv(sockConn,recvBuf,101,0);rn ::MessageBox(NULL,CString(recvBuf),_T(""),MB_OK);rn closesocket(sockConn);rn WSACleanup();rn rnrnrn按了按钮以后服务端阻塞,然后运行客户端:rnrnUINT ClientThread(LPVOID any)rnrnrn WSADATA wsaData;rn int err;rn int sendInt = (int)any;rn int *pSend = (int*)any;rn int Send = *pSend;rn char ASend[60] ;rn memset(ASend ,0,sizeof(ASend ));rn char * cSend = "";rn cSend = itoa(Send,ASend,10);rn char * sendTest = "hello";rn rn err = WSAStartup(0x101,&wsaData);rn if (err != 0)rn rn ::MessageBox(NULL,_T("WSAStartup Error"),_T("WSAStartup Error"),MB_OK);rn return 0;rn rn if (LOBYTE (wsaData.wVersion)!= 1 || HIBYTE (wsaData.wVersion)!= 1 )rn rn ::MessageBox(NULL,_T("WSAversion error"),_T("WSAStartup Error"),MB_OK);rn WSACleanup();rn return 0;rn rn SOCKET m_sockClient = socket(AF_INET,SOCK_STREAM,0);rn SOCKADDR_IN addrSrv;rn addrSrv.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");rn addrSrv.sin_family = AF_INET;rn addrSrv.sin_port = htons(6122);rn char* recvBuf = "";rn connect(m_sockClient,(SOCKADDR*)&addrSrv,sizeof(SOCKADDR));rn send(m_sockClient,sendTest,100,0);rn while(1)rn rn rn recv(m_sockClient,recvBuf,101,0);rn send(m_sockClient,recvBuf,100,0);rn Sleep(9000);rn ;rn closesocket(m_sockClient);rn WSACleanup();rn rnrnrnrn调试客户端,在第一个SEND的时候SENDTEST里内容是对的,可在服务端RECVBUF里面总是空的,何解?
救命!recv不到怎么办?
recv之前的select都正常,可惜recv报-1。rnrn仔细检查了没什么不对的。对方的是unix主机,请各位碰到这种情况的都rnrn讨论讨论!
recv接收不到字符串
在客户端发送bufrn iSend=send(sClient,buf,sizeof(buf),0);rn服务器端接收rn iLen = recv(sAccept,buf,sizeof(buf),0);rniLen和发送的长度一样,但就是在接收的buf 里面全是0 这个是怎么回事哦?rn先谢了rn
关于linux c socket send()recv()的问题
问题1 socket断开后(包括服务端主动断开或网络原因断开)再send()会不会溢出rn问题2 int a=recv()返回int =0或int=-1代表什么意思rn谢谢
Socket:客户端收不到数据
rn服务器端:rnusing System;rnusing System.Collections.Generic;rnusing System.Linq;rnusing System.Text;rnusing System.Threading;rnusing System.Net;rnusing System.Net.Sockets;rnusing System.IO;rnrnnamespace ServerConsolernrn class Programrn rn private TcpListener listener = null;rn //private Thread serverThread = null;rn //private Socket client = null;rn static void Main(string[] args)rn rn Program p = new Program();rn //p.serverThread = new Thread(new ThreadStart(p.StartServer));rn //p.serverThread.IsBackground = true;rn //p.serverThread.Start();rn p.StartServer();rn Console.ReadLine();rn rn private void StartServer()rn rn Console.WriteLine("Server Started!");rn listener = new TcpListener(IPAddress.Parse("192.168.0.1"), 10000);rn listener.Start();rn while (true)rn rn Socket client = listener.AcceptSocket();rn Console.WriteLine("0 Connected!", ((IPEndPoint)client.RemoteEndPoint).Address.ToString());rn NetworkStream stream = new NetworkStream(client);rn StreamWriter writer = new StreamWriter(stream);rn //StreamReader reader = new StreamReader("test.txt");rn //string text = string.Empty;rn string text = "this is a test";rn //dorn //rn //text = reader.ReadLine();rn Console.WriteLine(text); rn writer.Write(text);rn writer.Flush();rn rn // while (text != null);rn //client.Shutdown(SocketShutdown.Send);rn //client.Close();rn Console.WriteLine("Exiting....");rn //reader.Close();rn //writer.Close();rn //stream.Close();rn rn rn rnrn rnrn客户端:rnusing System;rnusing System.Collections.Generic;rnusing System.Linq;rnusing System.Text;rnusing System.Threading;rnusing System.Net;rnusing System.Net.Sockets;rnusing System.IO;rnrnnamespace ClientConsolernrn class Programrn rn //private Thread clientThread = null;rn //private TcpClient client = null;rn private void ConnectToServer()rn rn TcpClient client = new TcpClient("192.168.0.1", 10000);rn if (client.Connected)rn rn Console.WriteLine("Connected!");rn NetworkStream stream = client.GetStream();rn StreamReader reader = new StreamReader(stream);rn string text = string.Empty;rn dorn rn text = reader.ReadLine();rn Console.WriteLine(text);rn rn while (text != null);rn rn rn static void Main(string[] args)rn rn Program p = new Program();rn //p.clientThread = new Thread(new ThreadStart(p.ConnectToServer));rn //p.clientThread.IsBackground = true;rn //p.clientThread.Start();rn p.ConnectToServer();rn Console.ReadLine();rn rn rnrn为什么客户端收不到数据呢?
raw socket接收不到数据
初学网络编程,照网上的例子写了个sniffer程序,可是执行到recv的时候,就没有返回了,估计是超时。请高人指点:rnrn[code=C/C++]rn#include "StdAfx.h"rn#include "Sniffer.h"rnrn#define SIO_RCVALL _WSAIOW(IOC_VENDOR,1)rn#define BUFFER_SIZE 65535rnchar RecvBuf[BUFFER_SIZE];rnrnUINT SniffThreadFun(LPVOID pParam);rnvoid SignalHandler(int sig);rnrnSniffer::Sniffer(void)rn : stopSniff(true)rnrnrnrnSniffer::~Sniffer(void)rnrnrnrnbool Sniffer::InitSocket(void)rnrn int err;rn int sockOpt = 1;rn char localName[100];rn struct hostent *hostPtr;rn SOCKADDR_IN sockAddr;rnrn WORD versionRequired = MAKEWORD(1,1);rn err = WSAStartup(versionRequired, &wsaData);rn if(err == SOCKET_ERROR)rn return false;rn sockRaw = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);rn if (sockRaw == INVALID_SOCKET)rn return false;rn err = setsockopt(sockRaw, IPPROTO_IP, IP_HDRINCL, rn (char*)&sockOpt, sizeof(sockOpt));rnrn if (err == SOCKET_ERROR)rn return false;rn err = gethostname(localName, sizeof(localName)-1);rn if (err == SOCKET_ERROR)rn return false;rn hostPtr = gethostbyname(localName);rn if (hostPtr == NULL)rn return false;rn sockAddr.sin_addr = *(in_addr *)hostPtr->h_addr_list[0];rn sockAddr.sin_family = AF_INET;rn sockAddr.sin_port = htons(57274);rn err = bind(sockRaw, (PSOCKADDR)&sockAddr, sizeof(sockAddr));rn if (err == SOCKET_ERROR)rn return false;rn return true;rnrnrnbool Sniffer::StartSniff(void)rnrn stopSniff = false;rn int err;rn unsigned long arg = 1;rnrn err = ioctlsocket(sockRaw, SIO_RCVALL, &arg);rn if (err == SOCKET_ERROR)rn int errCode = WSAGetLastError();rn return false;rnrn AfxBeginThread(rn (AFX_THREADPROC)SniffThreadFun, rn (LPVOID)this, rn THREAD_PRIORITY_NORMAL, rn 0, 0, NULL);rnrn return true;rnrnrnbool Sniffer::StopSniff(void)rnrn stopSniff = true;rn Sleep(2000);rn int err;rn DWORD arg = 0;rn err = ioctlsocket(sockRaw, SIO_RCVALL, &arg);rn if (err = SOCKET_ERROR)rn return false;rnrn return true;rnrnrnvoid Sniffer::DisposeSocket(void)rnrn WSACleanup();rn closesocket(sockRaw);rnrnrnUINT SniffThreadFun(LPVOID pParam)rnrn Sniffer *snifferPtr = (Sniffer *)pParam;rnrn while(!snifferPtr->stopSniff)rn rn //[color=#FF0000]执行recv的时候没有返回[/color]rn if (recv(snifferPtr->sockRaw, RecvBuf, BUFFER_SIZE, 0))rn rn snifferPtr->recvCallback(snifferPtr->pObserver, RecvBuf);rn rn rnrn return 0;rnrn[/code]
关于SOCKET接收不到数据
发送端:rn结构体rntypedef struct head_packetrnrn char type[20]; //类型rn int length; //长度rn char aque[20]; //序列号 rn ST_HEAD_PACKET;rn发送数据:rn strncpy(head_package->type , "log" , sizeof("log"));rn head_package->length = strlen(head_package->type);rn strncpy(head_package->aque , "log" , sizeof("log"));rnrn writen(sd , head_package, sizeof(struct head_packet));rn函数:rnssize_t writen(int fd, const void *ptr, size_t n)rnrn size_t nleft;rn ssize_t nwritten;rnrn nleft = n;rn while (nleft > 0) rn if ((nwritten = write(fd, ptr, nleft)) < 0) rn if (nleft == n)rn return(-1); /* error, return -1 */rn elsern break; /* error, return amount written so far */rn else if (nwritten == 0) rn break;rn rn nleft -= nwritten;rn ptr += nwritten;rn rn return(n - nleft); /* return >= 0 */rnrn接收端:rn head_package = (ST_HEAD_PACKET *)malloc(sizeof(struct head_packet));rn memset(head_package , 0 , sizeof(struct head_packet));rn readn(sd , head_package , sizeof(head_package));rn printf("%s\n" , head_package->type);rn printf("%s\n" , head_package->aque);rn问题:rn接收端只能收到head_package->type 不能接收到head_package->aque
socket connect之后 只能recv到一次数据.
连接到www.baidu.com ,流程是rn1.建立socketrn2.connectrn3.send发送请求 //发送成功 send返回发送了381字节rn4.recv接收 //接收成功,接收到HTTP 200 OK等等rn5.send发送请求 //请求和第一次一样,发送成功,send返回381字节rn6.recv接收//返回一个空的字符串rn并没有用closesocketrnrn下面是我的发送和接收部分代码rnbool ajsocket::SendHttpsRequest(string& req) rnrn Ret = send( m_socket, req.c_str(), req.size(), 0 );rn if( Ret!= SOCKET_ERROR)rn wsprintf(buff," send %d chars. ok.\n",Ret);rn show( buff );rn elsern show( "send fail!\n" );rn return false ;rn rn return true;rnrnrnstring ajsocket::GetRequestResult() rn string result;rn bool finish = false;rn show("\n================receive================\n");rn while(finish==false)rn Ret = recv( m_socket, sockBuff, sizeof( sockBuff ), 0 );rn rn if(Ret == SOCKET_ERROR)rn wsprintf(buff,"receive socket ERROR..........code:%d .\n",WSAGetLastError());rn show(buff);rn return NULL;rn rn if(Ret > 0)rn result.append(sockBuff,Ret);rn else if(Ret==0) rn show(result.c_str());rn rn finish = true;rn elsern show("recv ERROR.\n");rn return NULL;rn rn rn show("\n============receive finish============\n");rn return result;rnrnrnrn运行结果:rnrnsend 381 chars. ok.rn================receive================rnHTTP/1.1 200 OKrn..........rn============receive finish============rnsend 381 chars. ok.rn================receive================rnrn============receive finish============
我的Socket接收不到数据???
我写了一个多线程Socket服务端应用,Listen()后开线程处理,当一个客户端连接后,立即在线程里用Receive接收连数据,接收正常,rn 然后,这个连接不关闭,当Client端再发送数据的时候就收不到了,怎么办???
SOCKET连接接收不到数据
现在手头有个项目要建立PHP(client)和JAVA(server)的SOCKET连接,传递数据:rnrn现在SOCKET连接建立是成功的,而且PHP发过来的测试数据,在SERVER端也是收的到的rnrn问题是SERVER发出的数据,在PHP接收不到。请问各位有何看法啊?rnrn背景资料:rn1.SERVER端发送数据应该是成功的(不确定),因为并没有任何报错rn2.PHP老是出现这样的警告:rnWarning: Call-time pass-by-reference has been deprecated - argument passed by value; If you would like to pass it by reference, modify the declaration of fsockopen(). If you would like to enable call-time pass-by-reference, you can set allow_call_time_pass_reference to true in your INI file. However, future versions may not support this any longer. in G:\AppServ\www\sock\index1.php on line 4rnrn第4行:if (! ($fd = fsockopen("192.168.0.103",8888,&$error_number,&$error_des,60)))rnrn3.PHP接受数据用的rnecho fgets($fd,100000);rnrn4. JAVA端发送数据是:rnOutputStream out = clientSocket.getOutputStream();rnPrintWriter out1 = new PrintWriter(out,true); rnout1.println("我是007");
Python 如何处理socket recv 接收的数据
客户端接收了一段数据 用字符串表示an = "11111111abc 123 ",使用unpack解析:rnno, ac, pa = struct.unpack('8s8s8s', an)rnprint no, ac, pa rnrn'11111111', 'abc0x000x000x000x000x00', '1230x000x000x000x000x00'rn我求助的是取字符串时如何把后面的0x00 去掉?谢谢!
socket 联网后recv没有返回数据
利用socket与www.baidu.com建立连接 发送get数据 但是收到的数据是0 麻烦帮忙看下下面的代码 谢谢rn- (void)viewDidLoadrnrn [super viewDidLoad];rn // Do any additional setup after loading the view, typically from a nib.rn rn rn [self Connect:@"www.baidu.com" content:nil];rnrnrn-(NSMutableString *)makeHttpHeader:(NSString*)hostNamernrn NSMutableString * header = [[NSMutableString alloc] init];rn rn [header appendFormat:@"GET "];rn [header appendFormat:@"HTTP/1.1\r\n"];rn [header appendFormat:KENTER];rn rn [header appendFormat:@"Host:"];rn [header appendFormat:hostName];rn [header appendFormat:@"\r\n\r\n"];rnrn rn NSLog(@"%@",header);rn rn return header;rn rnrnrnrn-(NSString*)getIpAddressorHost:(NSString*)theHostrnrn struct hostent * host = gethostbyname([theHost UTF8String]);rn rn if( !host )rn rn herror("resolv");rn return NULL;rn rn rn struct in_addr ** list = (struct in_adr**)host->h_addr_list;rn NSString * addressString = [NSString stringWithCString:inet_ntoa(*list[0])];rn rn NSLog(@"IPAddr is:%@",addressString);//这里的 IP地址 是对的 rn return addressString;rnrnrn-(void)Connect:(NSString*)hostName content:(NSString*)contentSendedrnrn if((sockfd = socket(AF_INET,SOCK_STREAM,0))== -1 )rn rn perror("SOCKET error");rn exit(1);rn rn rn their_addr.sin_family = AF_INET;rn their_addr.sin_addr.s_addr = inet_addr([[self getIpAddressorHost:hostName] UTF8String]);rn rn their_addr.sin_port = htons(80);rn bzero(&(their_addr.sin_zero),8);rn rn int conn = connect(sockfd , (struct sockaddr*)&their_addr , sizeof(struct sockaddr));rn rn NSLog(@"conn:%d",conn);rn rn if( conn != -1 )rn rn char readBuf[512]=0;rn rn int recvLen = 0;rn rn NSMutableString *httpContent = [self makeHttpHeader:hostName];rn rn if( contentSended != nil )rn rn [httpContent appendFormat:contentSended];rn rn rn NSData * data = [httpContent dataUsingEncoding:NSISOLatin1StringEncoding];rn ssize_t dataSended = send(sockfd,[data bytes],[data length],0);rn rn NSLog(@"Send:%d",(int)dataSended);//这里发送有成功的rn rn NSMutableString * readString = [[NSMutableString alloc]init];rn rn rn recvLen = recv(sockfd , readBuf,sizeof(readBuf),0);rn rn NSLog(@"len2:%d",recvLen);rn rn close(sockfd);rn rnrnrnrn这里使用的是 阻塞的方式 代码运行之后过一段时间会显示 len2:0rn也就是说没有接受到任何的东西,请问这个大概的原因在哪里?rnrn谢谢各位了!
BSD socket recv函数多接受了数据
描述一下具体情况:rn 服务端是winsock2, 客服端是bsd socketrn假设服务端发来了一个500字节大小的数据,客服端在执行下面的语句后rnchar buf[2048];rnint ret=recv(handlerSocket,buf,sizeof(buf),0); 问题出现了,ret会是一个大于500 && 小于2048的数,在buf数据中,前500字节正是服务端发来的数据,而后面的不知道是神马了。rn何解,望指教!
请教socket中recv()接受数据问题!
我的程序是接收数据部分,发送方发送一祯jpeg数据给我,先发送4个字节的jpeg数据总长度,之后发送jpeg数据。我的接收部分,把收到数据都放在array数组中,程序如下,但接收速度很慢,请问有和修改方法:rnint *leng;rnget_bytes =recv(m_ClientSocket,(char *)array,4,0 );rnleng=(int *)array;rngetnum=0;rndornrn dorn get_bytes =recv(m_ClientSocket,( char *)array+4+getnum,*leng-getnum,0 );rn while(get_bytes<0)rn getnum=getnum+get_bytes;rnwhile(getnum<*leng);
socket recv错误代码10053
socket是非阻塞模式,在connect的时候,就会报10035的错,后来while循环,一直尝试链接,得到错误代码10056,算是连接上了。send也成功了,但是就是在recv的时候,总是返回10053的错误。在网上查了查,有人说recv之前Sleep一下,在Sleep(10000)的时候,的确是recv到了,但是要是sleep时间变小一点,就又是返回10053错误。因为也是在别人的代码上改的,自己也是糊里糊涂的,代码太多了,就贴一点recv前面的部分吧。rnrn u_long iMode = 1;rn ioctlsocket(sock, FIONBIO, &iMode);rnrn while(newlines != 2 && bytesRead != HEADER_BUF_SIZE-1) rn rn FD_ZERO(&rfds);rn FD_SET(sock, &rfds);rn tv.tv_sec = timeout;rn tv.tv_usec = 0;rnrn if(timeout >= 0)rn selectRet = select(sock+1, &rfds, NULL, NULL, &tv);rn else rn selectRet = select(sock+1, &rfds, NULL, NULL, NULL);rnrn if(selectRet == 0 && timeout < 0)rn rn cout << "selectRet == 0 && timeout < 0" << endl;rn return -1;rn rn else if(selectRet == -1)rn rn cout << "selectRet == 0 && timeout < 0 else" << endl;rn return -1;rn rnrn [color=#FF0000]Sleep(10000);rn ret = recv(sock, headerPtr, 1,0);[/color]rnrn if(ret == -1)rn rn cout << "!error: read() in read_header()" << endl;rn int error=WSAGetLastError();rn cout< 400 Bad Requestrn rn 400 Bad Requestrn nginxrn rn rn 但是我在用Firefox的Live Http headers工具可以看到200的头部。好奇怪的问题。网上说是get请求语句有问题,但为什么一个在sleep之后就正常了,一个却总是400的结果。rn 我使用两个线程同时访问网址的。rn 希望大家都来帮帮忙,我本来就不是很懂得,还需要大家多多指教才好。先谢谢各位啦。rn
socket send和recv
如何让send出去的数据被recv收到后才发送下一条消息?rn send("17_1");rn send("18_1");rn Sleep(100);rn send("46_1");rn如果中间不加Sleep(100),最后一个数据无法收到,为什么rn用的是TCP
socket的 recv 问题
用 while((numbytes = recv(sockfd,recBuf,MaxRecvLen,0))!=-1)rn rn recBuf[numbytes]='\0';rn printf("\n\t********* %d *******",numbytes);rn printf("%s",recBuf);rn rn来得到所有的数据,但发现一个问题.rn有几时返回的numbytes 并不是MaxRecvLen 指定的长度rn比如 MaxRecvLen=10rn返回的长度有可能是rn10rn8rn10rn6rnrn而且当数据接收完没数据时运行 recv(sockfd,recBuf,MaxRecvLen,0)rn会特别的慢.rnrnrn比如.假设要读的文件长度是 95rn我用 recv 以每次读 100 个长度的方法。rn第一次运行recv 就把文件的内容全读进来了。rn这时 第二次运行recv 就会出现长时间的等待.rn估计要近10秒钟。这种情况怎么避免 ?
linux下socket的recv问题
我在socket编程中;使用select来同时处理多路输入流,但是有时select返回>0,即有有东西可读时,调用recv返回-1,且全局变量errno的值是32---Broken pipe。rn请问各位大虾,这是怎么回事???
socket recv()的问题?
如果server端send()10W个字节到协议缓冲区,协议缓冲区在发送数据给client的时候,可能不能一次性的吧数据传给client,比喻传了1W个字节,那么客户端就会有个FD_READ,我想问当客户端相应这个消息的时候,server端协议缓冲区能否继续发送剩余的9W个字节
socket recv 效率问题
问题:rnrn测试多线程程序并发rnrnsocket recv阻塞模式接收数据时 正常情况只用不到1msrnrn个别情况却达到了几秒钟rnrn怎么避免这种超时的现象
SOCKET recv 缓冲区问题
我知道 ,当我们调用recv的时候,是从缓冲区里面得到数据放到自己的buf里面的。我们不需要去关心缓冲区的数据到底是如何得到的,这个是协议处理的问题。rnrn但是我现在的问题是,当我们调用recv的时候。只是从接受缓冲区里面copy数据到我们的buf呢,还是拷贝完之后把拷贝成功的清除了。 形象点说就是:是copy-paste呢,还是cut-paste呢?
SOCKET recv接收数据不完整!
发送端:rn DWORD dwRead=0;rn char ch[4096];rn dorn rn dwRead=file.Read(ch,4096);rn if(dwRead!=0)rn send(nSock,ch,dwRead,0);rn rn while(dwRead>0);rn file.Close();rnrn接收端:rnrn char ch[4096];rn dorn rn memset(ch,0,4096);rn if(file.GetLength()==u2.szfile) //u2.szfile 是文件长度rn break;rn get=recv(sockConn,ch,4096,0);rn if(get!=0)rn file.Write(ch,get);rn rn while(get!=0);rnrn本机测试,多线程里发送多个文件,接收端时不时出现数据接收不完整情况。不是比原来大了就是小了。打开接收到了文件提示数据不完整无法打开。单个文件发送出错几率就很小。rn错在哪里,求助!
socket的send和recv出错
sock问题,上午程序还可以发和收字符串,下午改成发送结构不成功,又改成字符串可是不行了,为什么?急!服务器与客户端的初始化socket应该没问题!因发送是成功的!rnrnClient:发rn#define MAX_INFO 100rn char cTemp[MAX_INFO]="florence";rn int nByte = send(m_hSocket, cTemp, 10, 0);rn if ( nByte == SOCKET_ERROR )rn AfxMessageBox("Error occurred during send!");rn//nByte = 100,成功rnrnServer:收 rn#define MAX_INFO 100rnchar cTemp[MAX_INFO]="";rnint j = recv(m_hSocket, cTemp, 10, 0);rnj = GetLastError();rnAfxMessageBox(cTemp);rnrn//rncTemp = "";rn错误号:10057(由于套接字没有连接并且 (当使用一个 sendto 调用发送数据报套接字时) 没有提供地址,发送或接收数据的请求没有被接受。)rn真不知道是什么原因了?留email, 我可以给源代码!riversmall@sina.com
求教:关于socket的recv
本人使用该程序与一台本地通信设备建立数据通信.发送正常的帧(MsgList)时,recv方法能够接收到数据。但如果发送非正常的帧(即通信设备不会应答该帧),则程序就一直阻塞在recv方法那里,无法抛出异常。请教各位,怎么使得程序可以检查出对方无数据从socket发送过来,从而让recv抛出异常。使用select来检查吗?rn(附:本人使用while的原因是由于应答帧可能是由远程通信设备产生,经过本地设备中转而来,这中间需要消耗一定的时间,当发生超时时就不处理)rnimport socketrnimport structrnimport timernrnMsgStruct = ""rnmysock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)rntry:rn mysock.connect(('192.192.4.2',3000))rnexcept socket.error:rn sys.exit("Connect failed")rnMsgList =[150, 3, 192, 192, 4, 2, 192, 192, 4, 230, 0, 0, 0, 0, 0, 1, 0, 2, 17, 0, 0, 0, 4, 158]rnfor num in MsgList:rn MsgStruct = MsgStruct + struct.pack('@B',num)rntry:rn mysock.send(MsgStruct)rnexcept error:rn mysock.close()rnrntimeout = 5000rntStart = time.time( )rnwhile( 1 ):rn tFinish = time.time( )rn WaitTime = int( (tFinish - tStart)*1000 )rn if WaitTime > timeout:rn breakrn try:rn Msg = mysock.recv( 4096 )rn if Msg == ' ':rn raise errorrn except:rn continuernmysock.close()
socket  recv问题
基于TCP的连接,服务器端不断检测新的数据,为什么在客户端发送一次数据,服务器接受的数据无穷呢,例如:发送test,接受到的数据就是testtesttest....死循环状态,可我想发送一次接受一次数据,基于UDP的连接同样调用recvfrom()却正常,请大侠指点 rnwhile(TRUE) rn rn  int revl=recv(m_newSocket,(char*)dataBuf,100,0); rn  if(SOCKET_ERROR==revl) rn   rnAfxMessageBox("接受数据失败!"); rnreturn 0; rn   rn   rn  ::PostMessage(hwnd,WM_RECV,0,(LPARAM)dataBuf); //处理接受到的数据 rn
socket中send和recv
除了发送0个字节外,send什么时候返回值为0啊,好像都碰不到这种情况。rnrecv在udp时,是不是不会出现返回值为0这种情况啊》
SOCKET API的RECV
RECV函数使用需要线程的吧rn如何创建一个线程来使用recv呢?能否给点基本代码呢rn谢谢
Socket recv WSAGetLastError()= 10053;
这几天写了个DLL 需要用到Socket, 之前用我自己写的服务端测试是正常的 。 但是产品拿到手后 就出现问题了 套接字发送结构体 ,connect正常 这时我不发送一切正常, 但我发送命令后 recv 这里就报错了 10053。 可能是协议问题,协议也不清不楚的。 来大神帮我看看 小弟感激不尽![img=https://forum.csdn.net/PointForum/ui/scripts/csdn/Plugin/003/onion/3.gif][/img]贴上部分代码rn线程接收[code=c]DWORD WINAPI RecvProc(LPVOID lpParameter)rnrn //SerialportSocket* pLocal=(SerialportSocket*)lpParameter;rnrn SOCKET sock=((SerialportSocket::RECVPARAM*)lpParameter)->sock;rn HWND hwnd=((SerialportSocket::RECVPARAM*)lpParameter)->hwnd;rn DataFrameDispose::TMMIAutoTestATRsp RecvCommand = ((SerialportSocket::RECVPARAM*)lpParameter)->RecvCommand;rn BOOL flag=((SerialportSocket::RECVPARAM*)lpParameter)->Flag;rn //delete lpParameter; //释放内存的操作rnrn //接收rn DWORD dwTimeStart = ::GetTickCount();rn DWORD dwTimeMax = 10000;rn char recvBuf[sizeof(m_RecvCommand)]=0;//获取客户端发送的消息rn int retval;rnrn while(TRUE)rn rn flag = ((SerialportSocket::RECVPARAM*)lpParameter)->Flag;rn if (!(flag))rn rn break;rn rn retval=recv(sock,recvBuf,sizeof(recvBuf),0);rn int i =WSAGetLastError();rn memcpy(&(((SerialportSocket::RECVPARAM*)lpParameter)->RecvCommand), recvBuf, sizeof(recvBuf));rn if(SOCKET_ERROR==retval)rn rn break;rn rn rn return 0;rn[/code]rn发送消息rn[code=c]//发送消息rnBOOL SerialportSocket::SendSocketMessage(int iReceive,CString strReceive)rnrn int iResult;rn DataFrameDispose::TMMIAutoTestATCmd FrameCommand = m_DataDispose.ReceiveDispose(iReceive,strReceive);rn //CString i = "TMMIAutoTestATCmd: FrameH, AT^FM_AT_INIT_SETTING";rn iResult = send(m_socket,(char *)&FrameCommand,sizeof(FrameCommand),0);rn if (SOCKET_ERROR == iResult)rn rn return FALSE;rn rn elsern rn return TRUE;rn rn[/code]rnrn数据处理rn[code=c]rn//接收命令字符并处理成数据帧rnDataFrameDispose::TMMIAutoTestATCmd DataFrameDispose::ReceiveDispose(int iReceive,CString strReceive)rnrn BYTE CmdBuf[D_AT_CMD_MAX_LEN] = "";rn TMMIAutoTestFrameH FrameHeader = 0,0,0,0,0;rn TMMIAutoTestATCmd FrameCommand = FrameHeader,CmdBuf[D_AT_CMD_MAX_LEN];rnrn //数据帧帧头rn FrameHeader.DataType = DATA_TYPE_AT;rn FrameHeader.CommandType = iReceive;rn FrameHeader.DataLength = sizeof(FrameCommand);rn FrameHeader.EofFlag = 1;rn FrameHeader.RecordNum = 1;rnrn //数据帧rn FrameCommand.FrameH = FrameHeader;rn char *ch;rn ch = (LPSTR)(LPCTSTR)strReceive;rn //memcpy(CmdBuf,strReceive.GetBuffer(strReceive.GetLength()),strReceive.GetLength()); //将cstring放入byte数组rn int j = 0;rn for (int i = 0; i < strReceive.GetLength(); i++)rn rn FrameCommand.ATCmd[i] = *((BYTE*)ch++);rn if (FrameCommand.ATCmd[i] == 0)rn rn i--;rn rn rn rn return FrameCommand;rn[/code]rnrnrn还有就是结构体定义rnrn[code=c]public:rnrn //命令帧帧头信息数据结构定义rn typedef structrn rn BYTE DataType; //数据包内容的类型:AT数据类型(0xFF),整数类型(0x1)rn INT CommandType;rn INT DataLength; //表示该帧的长度,以字节为单位(包括帧头的11个字节,以及数据内容的长度)rn BYTE EofFlag; //表示该帧是否最后一帧,1表示是最后一帧,否则表示后面还有帧,DataLength < 4Krn INT RecordNum; //表示本次命令中(不是一帧内)包含的数据记录的个数rn TMMIAutoTestFrameH;rnrn //PC发送给PHONE的AT COMMAND数据结构定义rn #define D_AT_CMD_MAX_LEN (4096 - sizeof(TMMIAutoTestFrameH))rn typedef structrn rn TMMIAutoTestFrameH FrameH;rn BYTE ATCmd[D_AT_CMD_MAX_LEN];rn TMMIAutoTestATCmd;rnrnrn //TChgingInf数据结构定义rn typedef structrn rn INT ChgrOnStatus;rn INT ChgrType;rn INT ChgingStatus;rn INT ChgingCur;rn INT BattTemp;rn INT BattVol;rn INT ChgrVol;rn TChgingInf;rnrn //TGPSInf数据结构定义rn #define D_AT_RSP_IMEI_NUM_MAX_LEN (16)rn typedef structrn rn BYTE IMEINum[D_AT_RSP_IMEI_NUM_MAX_LEN];rn INT PhaseRatioX1000;rn INT TcxoOffsetHz;rn INT TcxoDriftHzX1000;rn INT CNRMean;rn INT SNR;rn TGPSInf;rnrn //GsensorInfo数据结构定义rn typedef structrn rn FLOAT dataX;rn FLOAT dataY;rn FLOAT dataZ;rn TGSensorInf;rnrn //IMEIInf数据结构定义如下:rn typedef structrn rn CString imei1;rn CString imei2;rn TIMEIInf;rnrn //MsensorInfo数据结构定义如下:rn typedef structrn rn FLOAT dataX;rn FLOAT dataY;rn FLOAT dataZ;rn TMsensorInfo;rnrn //TMMIAutoTestRspData数据结构定义rn #define D_AT_RSP_SW_VER_MAX_LEN (64)rn #define D_AT_RSP_PCB_NUM_MAX_LEN (32)rn #define D_AT_RSP_MSENSOR_D (3)rn #define D_AT_RSP_KEYPAD_PRESSED_MAX (10)rnrn typedef struct rn rn BYTE SwVersion[D_AT_RSP_SW_VER_MAX_LEN];rn BYTE PCBNum[D_AT_RSP_PCB_NUM_MAX_LEN];rnrn BYTE SimCardInf;rn BYTE TPLineInputStatus;rn BYTE HeadsetStatus;rnrn INT KeyStatus[D_AT_RSP_KEYPAD_PRESSED_MAX];rn INT BTDevNum;rn INT LightSensorVal;rn INT ProximitySensorVal;rnrn TChgingInf ChgingInf;rn TGPSInf GPSInf;rn TGSensorInf GSenforInf;rn TIMEIInf IMEIInf;rn TMsensorInfo MsensorInfo;rn TMMIAutoTestRspData;rnrnrn //PHONE回复给PC的AT RESPOND数据结构定义rn typedef structrn rn TMMIAutoTestFrameH FrameH;rn bool Success;rn TMMIAutoTestRspData RspData;rn TMMIAutoTestATRsp;rnrn[/code]
socket的recv乱码~求救~
c++用socket发送消息和文件。rn只是在接收端,我的电脑接受消息时会先出现一段乱码,再出现应该发送的信息,但是其他电脑都不会,为什么会这样~~~~rn发送端:rn#includern#includern#pragma comment (lib,"ws2_32.lib")rnusing namespace std;rnrnvoid main(void)rnrn WSADATA wsaData;rn if(WSAStartup(MAKEWORD(2,2),&wsaData)!=0)rn rn cout<<"Winsock初始化失败。"<>filename;rn send(SockConn,filename,strlen(filename)+1,0);rn cout<<"请输入文件的绝对路径(例如:d:\\\\example.txt):";rn cin>>filepath;rn HANDLE hFile=CreateFileA(filepath,GENERIC_READ,0,0,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,0);rn while(true)rn rn bRet=ReadFile(hFile,sendbuf,1024,&dwRead,NULL);rn if(bRet==FALSE)rn rn cout<<"文件读取错误。"<rn#includern#pragma comment(lib,"ws2_32.lib")rnusing namespace std;rnrnvoid main(void)rnrn WSADATA wsaData;rn if(WSAStartup(MAKEWORD(2,2),&wsaData)!=0)rn rn cout<<"Winsock初始化失败。"<>choice;rn if(choice=='N')rn rn cout<<"请输入服务器的IP地址:";rn cin>>ip_addr;rn rn rn SOCKADDR_IN addrClient;rn addrClient.sin_addr.S_un.S_addr=inet_addr(ip_addr);rn addrClient.sin_family=AF_INET;rn addrClient.sin_port=htons(5150);rnrn if(connect(sockClient,(SOCKADDR*)&addrClient,sizeof(SOCKADDR)) == SOCKET_ERROR)rn rn cout<<"连接出错。"<>filepath;rn HANDLE hFile=CreateFileA(filepath,GENERIC_WRITE,0,0,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,0);rn while(true)rn rn size=recv(sockClient,recvbuf,1024,0);rn count=size+count;rn bRet=WriteFile(hFile,recvbuf,size,&dwWrite,NULL);rn if(bRet==FALSE)rn rn cout<<"文件写入错误。"<
linux socket recv 段错误
本人在linux端做一个简单的socket客户端测试程序。rn[color=#FF0000]但是在运行过程中,执行到接收对方响应报文长度的代码处就报段错误rnread_count = recv(g_bf_socket, buffer, 4, 0);[/color]rnrn请高手帮忙分析分析是什么导致,我真的看不出代码哪里有问题啊?如果去掉这行代码就什么问题都没有。rnrnrn全部代码如下:rnrn[code=c]rn#include // for sockaddr_inrn#include // for socketrn#include // for socketrn#include // for printfrn#include // for exitrn#include // for bzero rn#includern#define BUFFER_SIZE 10240rnrn/************************************************************************/rn/* 客户端 */rn/************************************************************************/rn#define BIG_FRONT_END_IP ("192.168.10.146") //rn#define BIG_FRONT_END_PORT 9999 //rnint g_bf_socket; //rnstruct sockaddr_in g_bf_addr; //rnrnint bf_init(); //初始化与xxx通信相关的定义rnint bf_transaction(); //与xxx进行一次短连接,发送请求报文后接收响应报文rnint bf_connect(); //连接xxxrnrnconst char tran12345[] = rn rn "\rn \rn \rn xxxxxx\rn 123456\rn xxxxxx\rn 05\rn \rn xxxxxx\rn 01\rn \rn \rn \rn \rn \rn xxx\rn \rn \rn \rn xxxxxx\rn xxx\rn \rn \rn ";rnrnint main(int argc, char **argv) rnrn printf("start init...\n");rn //signal(SIGINT,SIG_IGN);rn //signal(SIGPIPE,SIG_IGN);rn //signal(SIGQUIT,SIG_IGN);rn ////signal(SIGTERM,EXIT);rn //signal(SIGUSR1,SIG_IGN);rn //signal(SIGCLD,SIG_IGN); rn if ( bf_init() == -1 )rn rn exit(1);rn rnrn if ( bf_transaction() == -1 )rn rn exit(1);rn rnrn return 0;rn rnrnint bf_init()rnrn struct sockaddr_in client_addr;rn bzero(&client_addr,sizeof(client_addr));rn client_addr.sin_family = AF_INET; //internet协议族rn client_addr.sin_addr.s_addr = htons(INADDR_ANY);//INADDR_ANY表示自动获取本机地址rn client_addr.sin_port = htons(0); //0表示让系统自动分配一个空闲端口 rnrn g_bf_socket = socket(AF_INET, SOCK_STREAM, 0);rn if ( g_bf_socket < 0 ) rn rn printf("Create Socket Failed!\n");rn return -1;rn rn elsern rn printf("Create Socket success.\n");rn rn if ( bind(g_bf_socket,(struct sockaddr*)&client_addr, sizeof(client_addr)) )rn rn printf("Client Bind Port Failed!\n"); rn return -1;rn rn elsern rn printf("bind success\n");rn rnrn bzero(&g_bf_addr, sizeof(g_bf_addr));rn g_bf_addr.sin_family = AF_INET; rn g_bf_addr.sin_addr.s_addr = inet_addr("192.168.10.146");rn g_bf_addr.sin_port = htons(BIG_FRONT_END_PORT); rnrnrnint bf_connect()rnrn if ( connect(g_bf_socket,(struct sockaddr*)&g_bf_addr, sizeof(g_bf_addr)) < 0 )rn rn return -1; rn rn rn return 0;rnrnrnrnint bf_transaction()rnrn char buffer[BUFFER_SIZE]; rn char szLen[5];rn int len, read_count;rnrn if ( bf_connect() == -1 )rn rn printf("connect fail.\n");rn return -1;rn rn elsern rn printf("connect success.\n");rn rn rn //发送4字节的请求报文长度rn bzero(szLen, sizeof(szLen));rn sprintf(szLen, "%04d", strlen(tran12345));rn len = send(g_bf_socket, szLen, 4, 0);rn printf("length:send content=[%s] real send length=[%d]\n", szLen, len);rn rn //发送请求报文体rn bzero(buffer, BUFFER_SIZE); rn strncpy(buffer, tran12345, strlen(tran12345));rn len = send(g_bf_socket, buffer, strlen(buffer), 0);rn printf("buffer length:%d, send length:%d\n", strlen(buffer), len);rnrn /*接收4字节的响应报文长度值*/rn bzero(szLen, sizeof(szLen));rn char sz[BUFFER_SIZE]=0;rn bzero(buffer, sizeof(buffer));rn read_count = recv(g_bf_socket, buffer, 4, 0);rn printf("need recv length=[%s] szLen=[%s]\n", read_count, szLen);rn rn //接收响应报文体rn bzero(buffer, BUFFER_SIZE); rn len = atoi(szLen);rn printf("len=[%d]\n", len);rn read_count = recv(g_bf_socket, buffer, len, 0); rn printf("response message length=[%d]\n", read_count);rn if ( read_count < 0 ) rn rn printf("Receive Data From xxx Failed!\n"); rn rn elsern rn printf("receive:%s\n", buffer);rn rnrn printf("one transaction cycle finish. app exit.\n"); rn close(g_bf_socket);rn g_bf_socket = -1;rnrnrn[/code]
相关热词 c#入门推荐书 c# 解码海康数据流 c# xml的遍历循环 c# 取 查看源码没有的 c#解决高并发 委托 c#日期转化为字符串 c# 显示问号 c# 字典对象池 c#5.0 安装程序 c# 分页算法