C++中使用Socket通信,在服务器端,如何实现接收数据和发送数据在不同的线程中

创建一个接收socket数据的线程,从port口接收数据后,再传入内部处理线程;
在内部处理线程执行结束后,再做成回复消息,想通过另一个线程,向接收数据的port口发送消息。
上面的设计,怎么使用另一个线程向port口发送消息呢?我实现的发送失败。

1个回答

首先呢,你需要确定一点,你的两个线程中用到的socket必须是同一个,你可以选择做成全局变量或者更常用的方法是做成单例类。然后你再考虑如何数据传递给另一个线程,这也很简单,数据传递可能会比较费劲,这个涉及到操作系统的知识,但是你可以也选择用一个全局的结构体或者用来存放数据的单例类,然后在发送线程中去检测他,方式也很多啦,阻塞非阻塞的都行。在linux下比较常见的就是select。或回调主动发送。

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
ios客户端向服务器端发送数据以及接收数据要如何实现?
百度说要用jason或者xml封装数据后再发送到服务器,我想问问用jason好还是xml好一点(发送的数据比较简单,就是一条数据包含几个字符串和数字),如何封装&解析?服务器端要如何实现?还有就是用jason或者xml需要在下载什么包还是xcode自带?有没有什么资料或者例子参考?rn本人新手,请多多指教,谢谢
线程中发送数据
我在程序中启动如下线程后,在pSocket->Close();处弹出ASSERT,请问是怎么回事?如何在该线程结束后关闭并析构该socket?rnrnUINT StartSendThread(LPVOID pParam)rnrn CClientSocket* pSocket = (CClientSocket*)((ParamStruct*)pParam)->pSock;rn CFileSendDlg* pDlg = (CFileSendDlg*)((ParamStruct*)pParam)->pDlg;rnrn for(char i='a'; i<'z'; i++)rn rn char buff = i;rn pSocket->Send(&buff, 1);rn rnrn pSocket->Close();rn rn return(0);rn
socket服务器端如何接收数据?
想问问我写一个服务器端监控某个端口,rn如果有数据发到这个端口,就把发过来的数据读到某个文本框里面rnrn但是我不知道用什么代码可以判断是否有数据已经发到这个端口rn如果用代码:rnSystem.Net.Sockets.Socket socket1 = socket.Accept();rn如果实际情况没有任何数据发到这个端口,程序好像就死了一样rn我想知道有没有什么属性判断那个端口有连接?rnrn因为初接触socket,所以很多概念都没搞清楚,rn如果一个客户端发了很多信息到服务器端口,服务器接收到那个客户端的请求并rn读完所有buffer数据后,是不是自动就断开了通信,那么下次客户端再发数据rn到服务器端,就认为是新的连接请求吗?rn
线程中怎么使用串口发送数据?
如题,我好像记得线程不能使用控件,那怎么给串口发送数据呢。
『高分』如何实现串口发送数据同时处理接收数据(C/C++)
现已完成串口的单工的发送和读取,源代码如下:rn[code=C/C++]rn#include rn#include rn#include rn#include rn#include rn#include rn#include rn#include rn#include rn#include rn#include rnrnrnrnunsigned char ch_read(int fd);rnint asy_open(char *Port, int Baud);rnrn#define DataTimeout 0rn#define UART_DEBUGrnrn/* Main program */rnrnstatic void useage()rnrn printf("uart test for 2410--------------------\n");rn printf("brate:115200\n");rn printf("example:\n");rn printf("uart3 send--------: #uarttest -3 -s \n");rn printf("uart3 receive------: #uarttest -3 -r \n");rnrnrnrnrnrnrnrnrnint main(int argc, char **argv)rnrn int fd;rn char portname[15];rn int e;rn unsigned char ch;rn char buf[20] = "hello world!\n";rn char rvbuf[100];rn char rv_Pos;rn int ret;rn int i,n,recvbytes,flag; rnrn struct timeval timeout;rn rn timeout.tv_sec = 0;rn timeout.tv_usec = 0;rn rn if(argc!=3)rn rn useage();rn return -1;rn rn sprintf(portname,"/dev/ttyS%d",argv[1][1]-49);rn fd = asy_open(portname,B115200); rn if(argv[2][1]=='s')rn rn while(1)rn rn write(fd,buf,strlen(buf));rn sleep(1);rn rn return 0;rn rn printf("read-------------\n");rn rv_Pos=0;rn /*rn while(1)rn FD_ZERO (&rset);rn if (fd >= 0)FD_SET (fd, &rset);rnrn e = select (fd + 1, &rset, NULL, NULL, &timeout);rnrn if (e > 0)rn if (fd >= 0 && FD_ISSET (fd, &rset))rn FD_CLR(fd, &rset);rn //ret = ch_read(fd);rn read(fd,&ch,1);rn //if(ret > 0)rn printf("ch = %x\n",ch);rn rn rn rn */rn memset(rvbuf,0,100);rn while(1)rn rn //n=read(fd,&ch,1);rn recvbytes=0;rn ioctl(fd, FIONREAD, &recvbytes);rn //if there are some chars in the input buffer, then receive them.rn if(recvbytes>0)rn rn flag=1;rn while(1) rn rn n=read(fd,&ch,1); rn if(n<0)rn rn //printf("Serial COM receiving data error!\n");rn if(errno==EAGAIN)//Resource temporarily unavailablern break;//break from the while looprn elsern perror("read com error");rn rn else if(n>0)rn rnrn if((rv_Pos+1)>100)rn rn printf("1The input buffer is overflowed!\n");rn rvbuf[rv_Pos]='\0';rn printf(rvbuf);rn printf("\n");rn rv_Pos=0;rn rn elsern rn rvbuf[rv_Pos]=ch;rn rv_Pos++;rn rn rn elsern rn //rvbuf[rv_Pos]='\0';rn //printf(rvbuf);rn //printf("\n");rn //rv_Pos=0;rn break;rn rn rn rn if((recvbytes==0)&&(flag==1))rn rn rvbuf[rv_Pos]='\0';rn flag=0;rn printf(rvbuf);rn printf("\n");rn rv_Pos=0;rn rn rn return 0;rnrnrnrnrnrn/* Char processing */rn/*rnunsigned char ch_read(int fd)rn rn unsigned char ch,temp1,buf[10] = 0;rn int ret,i;rnrn ret = read(fd,&ch,1);rn if(!ret || ch != 0x55)return 0;rn fprintf(stderr,"ch = %x\n",ch);rnrn ret = read(fd,&ch,1);rn if(!ret || ch != 0x55)return 0;rn fprintf(stderr,"ch = %x\n",ch);rnrn ret = read(fd,&ch,1);rn if(!ret)return 0;rn fprintf(stderr,"ch = %x\n",ch);rnrn temp1 = ch;rn ret = read(fd,&ch,1);rn if(!ret)return 0;rn fprintf(stderr,"ch = %x\n",ch);rn if((temp1 + ch) != 0xff)return 0;rnrn// if((ch == 0x22) || (ch == 0x13) || (ch == 0x43) || (ch == 0x23))rn return temp1;rn rnrn*/rnrnrn/* Uart open fuction */rnrnint asy_open(char *Port, int Baud)rnrn struct termio SerialParameters;rn int i, fd;rnrn //We want to open the port in nodelay mode, so we are informed if thern // port cannot be opened. rn if ((fd = open (Port, O_RDWR | O_NDELAY)) == -1) rn #ifdef UART_DEBUGrn fprintf (stderr, "asy_open: Cannot open port %s\n", Port);rn #endifrn return -1;rn rnrn // Now change the rest of the parameters - non-canonical input, etc. rn if (ioctl (fd, TCGETA, &SerialParameters) == -1) rn #ifdef UART_DEBUGrn fprintf (stderr, "asy_open: Cannot ioctl (get) on port %s. Errno = %d\n", Port, errno);rn #endifrn return -1;rn rnrn SerialParameters.c_cflag = Baud | CS8 | CLOCAL | CREAD | HUPCL;rn SerialParameters.c_lflag &= ~ICANON;rnrn SerialParameters.c_lflag = 0;rn SerialParameters.c_oflag = 0;rn SerialParameters.c_iflag = IGNBRK | IGNPAR;rn for (i = 0; i < NCC; i++)rn SerialParameters.c_cc[i] = (unsigned char) 0;rn SerialParameters.c_cc[VMIN] = (unsigned char) 0;rn SerialParameters.c_cc[VTIME] = (unsigned char) DataTimeout;rnrn if(ioctl (fd, TCSETA, &SerialParameters) == -1) rn #ifdef UART_DEBUGrn fprintf (stderr, "asy_open: Cannot ioctl (set) on port %s. Errno = %d\n", Port, errno);rn #endifrn return -1;rn rnrn return fd;rnrn[/code]rn如何实现当串口发送数据时,如果有数据进来先读取串口数据并显示?
线程中创建TIdUDPServer 如何接收数据
如题
CSocket对象在线程中如何接收数据!!!!
本人在对话框类的OnInitDialog()中创建了一个CSocket套接字rn又自定义了一个线程类继承自CWinThread,在其Run()方法中我向让其一直不停的接收消息,代码是:rn m_uDlg->m_uSocket.ReceiveFrom(buff, 10, szIP, uPort, 0);rn CString str(buff);rn m_uDlg->m_edit1.SetWindowText(str);rn Sleep(50);rn但程序编译没有错误,但运行时自动终止。这问题出在哪里啊??rn秦各位大侠帮忙,感激不尽!!!rn
使用系统文件实现socket通信--服务器端搭建
如何使用系统自带文件实现socket通信 1.首先搭建服务器端 注意: 这里创建文件是在Xcode的OSX下面的命令行创建的 因为一会客户端使用的iOS模拟器,而Xcode是不能同时运行两个模拟器的 具体就是 新建工程 >> OS X >> Application >> command Lind Tool 实现socket通信无论是客户端还是服务器端都需要引
线程里实现SOCKET通信
我在线程里创建了TCLIENTSOCKET是BLOCKING方式,我如何在得知SOCKE连接不正常时,不停的去连接SERVER?具体说,就是如何在线程中实现消息接收。
socket通信-服务器端
服务器 新建工程,Base class选择QWidget,在工程文件tcpServer.pro中添加一行代码:QT += network。 QT += core gui QT += network ui中添加一个label,用于显示状态信息。 在widget.h文件中做以下更改。 添加头文件:#include<QtNetwork/QtNetwork>添加private对象:QTcpServer *t
MFC实现客户端和服务器端socket通信,使用多线程分别进行收发数据,并在线程中操作界面
CClientSocket *m_pClientSocket = CClientSocket::getInstance();rnBOOL isReceive;rnBOOL isSend;rnDWORD WINAPI ThreadSend(LPVOID lpParam)rnrn BYTE buffOpen[] = 0xFE,0xEF,0x08,0x50,0x02,0x00,0x00,0x0A;rn BYTE buffClose[] = 0xFE,0xEF,0x08,0x50,0x02,0x00,0x01,0x0A;rn CClientSocket *socket = CClientSocket::getInstance();rn socket->Attach((SOCKET)lpParam);rn CtestClientDlg *dlg = (CtestClientDlg*)AfxGetApp()->GetMainWnd();rn if (isSend)rn rn int i = m_pClientSocket->Send(buffOpen,sizeof(buffOpen),0);rn if (i > 0)rn rn dlg->GetDlgItem(IDC_STATIC)->SetWindowTextW(_T("发送成功"));rn rn elsern dlg->GetDlgItem(IDC_STATIC)->SetWindowTextW(_T("发送成功"));rn rn Sleep(100);rn return 0;rnrnrnDWORD WINAPI ThreadReceive(LPVOID lpParam)rnrn CClientSocket *socket = CClientSocket::getInstance();rn socket->Attach((SOCKET)lpParam);rn CtestClientDlg *dlg = (CtestClientDlg*)AfxGetApp()->GetMainWnd();rn BYTE buf[20];rn while (isReceive)rn rn m_pClientSocket->Receive(buf,20);rn if (buf[6] == 0x0B && buf[7] == 0x01)rn rn dlg->GetDlgItem(IDC_STATIC)->SetWindowText(_T("进站:ATM站1到了"));rn rn if (buf[6] == 0x0B && buf[7] == 0x00)rn rn dlg->GetDlgItem(IDC_STATIC)->SetWindowText(_T("出站:离开ATM站1"));rn rn if (buf[6] == 0x0C && buf[7] == 0x01)rn rn dlg->GetDlgItem(IDC_STATIC)->SetWindowText(_T("进站:ATM站2到了"));rn rn if (buf[6] == 0x0C && buf[7] == 0x00)rn rn dlg->GetDlgItem(IDC_STATIC)->SetWindowText(_T("出站:离开ATM站2"));rn rn if (buf[6] == 0x0D && buf[7] == 0x01)rn rn dlg->GetDlgItem(IDC_STATIC)->SetWindowText(_T("进站:ATM站3到了"));rn rn if (buf[6] == 0x0D && buf[7] == 0x00)rn rn dlg->GetDlgItem(IDC_STATIC)->SetWindowText(_T("出站:离开ATM站3"));rn rn if (buf[6] == 0x0E && buf[7] == 0x01)rn rn dlg->GetDlgItem(IDC_STATIC)->SetWindowText(_T("进站:交通站1到了"));rn rn if (buf[6] == 0x0E && buf[7] == 0x00)rn rn dlg->GetDlgItem(IDC_STATIC)->SetWindowText(_T("出站:离开交通站1"));rn rn if (buf[6] == 0x0F && buf[7] == 0x01)rn rn dlg->GetDlgItem(IDC_STATIC)->SetWindowText(_T("进站:交通站2到了"));rn rn if (buf[6] == 0x0F && buf[7] == 0x00)rn rn dlg->GetDlgItem(IDC_STATIC)->SetWindowText(_T("出站:离开交通站2"));rn rn if (buf[6] == 0x10 && buf[7] == 0x01)rn rn dlg->GetDlgItem(IDC_STATIC)->SetWindowText(_T("进站:交通站1到了"));rn rn if (buf[6] == 0x10 && buf[7] == 0x00)rn rn dlg->GetDlgItem(IDC_STATIC)->SetWindowText(_T("出站:离开交通站1"));rn rn rn rn socket->Detach();rn socket->Close();rn Sleep(100);rn return 0;rnrnvoid CtestClientDlg::OnBnClickedButtonConnect()rnrn // TODO: 在此添加控件通知处理程序代码rn if(m_pClientSocket->Connect(CString("192.168.1.229"),UINT(8234)))rn rn AfxMessageBox(_T("连接成功"));rn rn elsern AfxMessageBox(_T("连接失败"));rnrnrnvoid CtestClientDlg::OnBnClickedButtonSend()rnrn // TODO: 在此添加控件通知处理程序代码rn isSend = TRUE;rn isReceive = FALSE;rn DWORD idThread;rn HANDLE hThread = CreateThread(NULL,0,ThreadSend,(LPVOID)(m_pClientSocket->Detach()),0,&idThread);rnrnvoid CtestClientDlg::OnBnClickedButtonReceive()rnrn // TODO: 在此添加控件通知处理程序代码rn isReceive = TRUE;rn isSend = FALSE;rn DWORD idThread;rn HANDLE hThread = CreateThread(NULL,0,ThreadReceive,(LPVOID)(m_pClientSocket->Detach()),0,&idThread);rnrn这里我使用的是单例模式的socket,每次点过发送再点接收或者反过来都还是会出现ASSERT(pState->m_hSocketWindow != NULL);错误,我知道是因为线程切换时socket分离的问题,可是不知道怎么改才能对,请各位指教
C# 中使用SOCKET通信
rnrnnamespace 城市燃气管网泄漏监测远程通讯系统rnrn public partial class frmTextLink : Formrn rn public frmTextLink()rn rn InitializeComponent();rn rnrn //以下是新加的rn private IPAddress myIP = IPAddress.Parse("127.0.0.1");rn private IPEndPoint MyServer;rn private Socket sock;rn private Socket handler;rn private static ManualResetEvent Done = new ManualResetEvent(false);rn //以上是新加的rnrn private void button1_Click(object sender, EventArgs e) //开始监听按钮rn rn tryrn rn myIP = IPAddress.Parse(textBox1.Text);rn rn catch MessageBox.Show("您输入的IP格式不正确,请重新输入"); rnrn tryrn rn MyServer = new IPEndPoint(myIP, Int32.Parse(textBox2.Text));rn sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);rn sock.Bind(MyServer);rn sock.Listen(50);rnrn toolStripStatusLabel1.Text = " 主机 " + textBox1.Text + " 端口 " + textBox2.Text + " 开始监听....";rnrn Thread thread = new Thread(new ThreadStart(targett));rn thread.Start();rnrn rn catch (Exception ee)rn rn toolStripStatusLabel1.Text = ee.Message;rn rnrn rnrn private void targett()rn rn while (true)rn rn //设为非终止rn Done.Reset();rnrn //异步开始接收rn sock.BeginAccept(new AsyncCallback(AcceptCallback), sock);rnrn //阻塞线程,知道收到信号rn Done.WaitOne();rn rn rnrn private void AcceptCallback(IAsyncResult ar)rn rn //设为终止rn Done.Set();rnrn //获取状态rn Socket listener = (Socket)ar.AsyncState;rnrn //结束异步接收,并获取结果rn handler = listener.EndAccept(ar);rnrn //创建自定义类对象实例rn StateObject state = new StateObject();rn state.workSocket = handler;rn toolStripStatusLabel1.Text = "与客户建立连接";rnrn tryrn rn byte[] byteData = System.Text.Encoding.BigEndianUnicode.GetBytes("准备完毕,可以通话!" + "\n\r");rnrn //开始异步发送数据rn handler.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), handler);rnrn rn catch (Exception ee)rn rn MessageBox.Show(ee.Message);rn rnrn //定义线程rn Thread thread = new Thread(new ThreadStart(rec));rnrn //开始接收数据线程rn thread.Start();rnrn rnrn private void SendCallback(IAsyncResult ar)rn rn tryrn rn //获取状态rn handler = (Socket)ar.AsyncState;rnrn //结束发送rn int bytesSent = handler.EndSend(ar);rn rnrn catch rn rnrn private void rec()rn rn StateObject state = new StateObject();rn state.workSocket = handler;rnrn //开始异步接收数据rn handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);rn rnrn private void ReadCallback(IAsyncResult ar)rn rn //获取状态rn StateObject state = (StateObject)ar.AsyncState;rn Socket tt = state.workSocket;rnrn //结束异步读取数据,并获取结果rn int bytesRead = handler.EndReceive(ar);rnrn //贮存数据rn state.sb.Append(System.Text.Encoding.BigEndianUnicode.GetString(state.buffer, 0, bytesRead));rnrn //转换为字符串rn string content = state.sb.ToString();rnrn //清楚state.sb内容rn state.sb.Remove(0, content.Length);rnrn //向richTextBox1写数据rn richTextBox1.AppendText(content + "\r\n");rnrn //重新开始接收rn tt.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);rn rnrn private void button3_Click(object sender, EventArgs e) //停止监听按钮rn rn tryrn rn sock.Close();rn toolStripStatusLabel1.Text = " 主机 " + textBox1.Text + " 端口 " + textBox2.Text + " 停止监听!";rnrnrn rn catchrn rn MessageBox.Show("监听尚未开始,关闭无效!");rn rn rnrn private void button2_Click(object sender, EventArgs e) //发送信息按钮rn rn tryrn rn byte[] byteData = System.Text.Encoding.BigEndianUnicode.GetBytes(richTextBox2.Text+"\n\r");rnrn //异步开始发送数据rn handler.BeginSend(byteData,0,byteData.Length,0,new AsyncCallback(SendCallback),handler);rn rn catch (Exception ee)rn rn MessageBox.Show(ee.Message);rn rn rnrnrnrnrn rnrnrn客户端代码:rnrnnamespace 异步客户端rnrn public partial class Form1 : Formrn rn public Form1()rn rn InitializeComponent();rn rnrn private IPAddress myIP = IPAddress.Parse("127.0.0.1");rn private IPEndPoint MyServer;rn private Socket sock;rn private static ManualResetEvent connectDone = new ManualResetEvent(false);rn private static ManualResetEvent sendDone = new ManualResetEvent(false);rnrn private void button1_Click(object sender, EventArgs e) //请求连接rn rn tryrn rn myIP = IPAddress.Parse(textBox1.Text);rn rn catch MessageBox.Show("您输入的IP格式不正确,请重新输入"); rnrn tryrn rn MyServer = new IPEndPoint(myIP, Int32.Parse(textBox2.Text));rn sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);rn sock.BeginConnect(MyServer,new AsyncCallback (ConnectCassback),sock);rn connectDone.WaitOne();rn rn catch(Exception ee)rn rn MessageBox.Show(ee.Message);rn rn rnrn private void ConnectCassback(IAsyncResult ar)rn rn tryrn rn //获取状态rn Socket client = (Socket)ar.AsyncState;rn client.EndConnect(ar);rnrn //自动发送数据rn tryrn rn byte[] byteData = System.Text.Encoding.BigEndianUnicode.GetBytes("准备完毕,可以通话!" + "\n\r");rnrn //异步开始发送rn sock.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), sock);rnrn rn catch (Exception ee)rn rn MessageBox.Show(ee.Message);rn rnrn toolStripStatusLabel1.Text = " 主机 " + textBox1.Text + " 端口 " + textBox2.Text + " 建立连接!";rnrn //定义线程rn Thread thread = new Thread(new ThreadStart(targett));rnrn //开始接收线程rn thread.Start();rnrn //设为终止rn connectDone.Set();rn rn catch rn rnrn private void SendCallback(IAsyncResult ar)rn rn tryrn rn //获取状态rn Socket client = (Socket)ar.AsyncState;rnrn //设为终止rn sendDone.Set();rn rn catch (Exception ee)rn rn MessageBox.Show(ee.Message);rn rn rnrn private void targett()rn rn tryrn rn StateObject state = new StateObject();rn state.workSocket = sock;rnrn //开始异步接收数据rn sock.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);rnrn rn catch (Exception ee)rn rn MessageBox.Show(ee.Message);rn rn rnrn private void ReceiveCallback(IAsyncResult ar)rn rn tryrn rn //获取状态rn StateObject state = (StateObject)ar.AsyncState;rn Socket client = state.workSocket;rnrn //结束异步读数据,并获取结果rn int bytesRead = client.EndReceive(ar);rnrn //储存数据rn state.sb.Append(System.Text.Encoding.BigEndianUnicode.GetString(state.buffer, 0, bytesRead));rn string aa = state.sb.ToString();rnrn //清除state.sbrn state.sb.Remove(0, aa.Length);rnrn richTextBox1.AppendText(aa + "\r\n");rnrn //读取未读数据rn client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);rnrn rn catch rn rnrn private void button2_Click(object sender, EventArgs e) //发送信息rn rn byte[] byteData = System.Text.Encoding.BigEndianUnicode.GetBytes(richTextBox2.Text);rnrn //开始异步发送数据rn sock.BeginSend(byteData,0,byteData.Length,0,new AsyncCallback(SendCallback),sock);rn rnrn private void button3_Click(object sender, EventArgs e) //关闭连接rn rn rn tryrn rn sock.Close();rn toolStripStatusLabel1.Text = " 主机 " + textBox1.Text + " 端口 " + textBox2.Text + "断开连接!";rnrn rnrn catch MessageBox.Show("连接尚未建立,断开无效!"); rn rnrn rnrnrnrn这是服务器端和客户端的代码。rn(1)我测试用的IP是127.0.0.1, 端口6688,每次点击客户端“关闭连接”时服务器端程序就退出。不知道为什么?rn(2)当我想用自己电脑的IP时,点击服务器端的“开始监听”,总是在窗体下方显示“在其上下文中,该请求的地址无效”rnrn
串口通信多线程接收数据,发送数据
串口通信,多线程接收数据,并可以发送数据
串口发送数据网口接收数据
串口自动发送方数据,网口接收数据,可运行,只要修改下网口参数-Automatic sending serial data, Ethernet port to receive data, can run as long as the modified parameters of the net mouth
SOCKET通信,接收数据分段。
我有个客户端,不停地在接收服务端发送过来的数据。rn例:rn第一行数据rn第二行数据rn第三行数据 rn我接收的BYTE数组大小为1024,可以看出以上的数据长度并没有超出1024,rn我的问题是,以上三行数据,我经常会分段收到,一次接收并没有收到完整的三行数据,而是,可能要分两次才能收到完整的。rn用TCP调试助手并没有这样的问题,请问如何解决?rnrnrn[code=csharp]rn if (sockClient.Poll(100, SelectMode.SelectRead))rn rn length = sockClient.Receive(arrMsg); // 接收数据,并返回数据的长度;rnrn rn[/code]
消息队列发送数据和接收数据
消息队列发送数据和接收数据
udp的发送数据和接收数据
1.发送数据 String ip = (String) SPUtils.get(IP_INFO, defaultIp, this); //获取本地ip地址 InetAddress receiverHost = InetAddress.getByName(ip); byte[] titleByte =
发送数据,接收数据,处理数据
该视频面向有一定开发经验的IOS开发人员,视频主要通过实际上线项目,讲解蓝牙的搜索,连接,手机发送数据,手机接收数据,并处理返回的数据,另外这个是实战项目,包括各个关键的技术点都会提到,还有一些自定义的控件,比如进度条,自定义拖动控件等等
串口发送数据接收数据问题。
对串口也是一无所知,做串口的底层开发。rnrn想请教大神,一个串口能发送数据,然后自己接收数据么?rnrn我这样写完 用虚拟串口测试 开启两个程序可以互相收发rnrn开启一个程序,打开串口,进去发送数据没有反应。订阅事件Sp1_DataReceived不触发。rnrn求大神帮忙rn[code=csharp]rn private void Form1_Load(object sender, EventArgs e)rn rn if (cbCom.Items.Count > 0)rn rn cbCom.SelectedIndex = 0;rn sp1.ReceivedBytesThreshold=1;rn sp1.BaudRate = 9600;rn sp1.DtrEnable = true;rn sp1.RtsEnable = true;rn sp1.ReadTimeout = 1000;rn sp1.ReceivedBytesThreshold = 1;rn sp1.DataReceived += new rn SerialDataReceivedEventHandler(this.Sp1_DataReceived);rn sp1.Open();rn rn rn private void Sp1_DataReceived(object sender, SerialDataReceivedEventArgs e)rn rn if (sp1.IsOpen) rn rnrn DateTime dt = DateTime.Now;rn txtReceived.Text += dt.GetDateTimeFormats('f')[0].ToString() +"\r\n";rn tryrn rn Byte[] receivedData = new Byte[sp1.BytesToRead]; rn sp1.Read(receivedData, 0, receivedData.Length); rn AddContent(new UTF8Encoding().GetString(receivedData));rn rn catch (System.Exception ex)rn rn MessageBox.Show(ex.Message, "出错提示!!!!!");rn txtSendStr.Text = "";rn rn rn elsern rn MessageBox.Show("请打开某个串口", "错误提示");rn rn rn[/code]
UDP协议接收数据与发送数据
UDP: 把数据打包 数据有限制 不建立连接 速度快 不可靠 一些需要用到的方法: InetAddress 类: tring getHostAddress() 返回 IP 地址字符串(以文本表现形式)。 String getHostName() 获取此 IP 地址的主机名。 static InetAdd...
服务器端如何向客户端发送数据?
我用post方法向服务器端发送了一个用户名和密码,想利用php实现服务器对该行为的响应,返回一个登录成功的字符串,该如何实现呢?客户端又该如何获得这个字符串呢?
socket用线程实现客户端和服务器端连续发送数据
线程+socket实现像QQ一样连续发送消息
在vue中使用SockJS实现webSocket通信
简单介绍 基于webSocket通信的库主要有 socket.io,SockJS,这次用的是 SockJS。 前提 这里我们使用sockjs-client、stomjs这两个模块,要实现webSocket通信,需要后台配合,也使用相应的模块。 关于实时通信 实现实时通信,我们通常有三种方法: ajax轮询 ajax轮询的原理非常简单,让浏览器每隔几秒就像服务器发送一个请求,询问服务器是...
WPF内实现与串口发送数据和接收数据
与串口发送数据和接收数据,在此作一个简单的Demo.此Demo可以实现按下硬件按钮,灯亮,发送灯状态数据过来。并且可以实现几个灯同时亮,发送灯的状态数据过来。PC端实现点击按钮让硬件灯亮。 此处为4个灯,发送过来的数据:0代表暗,1代表亮。列如:1010代表1号灯和3号灯亮,2号和4号灯暗。 发送过去的数据:0代表1号灯亮,1代表1号灯灭、2代表2号灯亮,3代表2号灯灭、4代表3号灯亮,5代表3
Log4j2实现不同线程不同级别日志输出到不同的文件中
Log4j2实现不同线程不同级别日志输出到不同的文件中 源码+log4j jar包
C# Scoket异步通讯实现(发送数据、接收数据)
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; namespace TCP_Server { class Progra
Socket通信案例--实现发送与接收数据
客户端: import socket client = socket.socket() client.connect((&quot;localhost&quot;,6969)) while True: msg = input(&quot;我要发数据&amp;gt;&amp;gt;:&quot;).strip() print(&quot;开始发送数据: &quot;+msg) client.send(msg.encode(&quot;UTF-8&quot;)) cl...
使用TCustomWinsocket时,发送数据和接收数据不一致的问题
在使用Bc6中TCustomWindsocket的ReceiveBuf函数接收数据时,有时经常会出现接收到的数据长度小于发送的数据长度。好像是由于Tcp数据分段引起的,而我传送的数据是自定义的格式化数据,一分段就麻烦大了,有没有什么办法能解决这个问题?有没有什么比较简单的方法,使得发一次数据,接收方只需要接收一次次就可以把数据完整的接收下来?
数据报实现简单的客户端发送数据,服务端接收数据
客户端 public static void main(String[] args) { // TODO Auto-generated method stub //创建一个数据报 DatagramSocket socket=null; //创建一个数据包 DatagramPacket packet=null; try { //实例化数据报 socket=new
Socket实现通信,实时接收数据以及发送数据
公司要做一个视频采集socket通信的项目,第三方服务端已经提供好了服务,让我们对接,但是目前ui还没有,所以就暂时先自己写个小demo测试一下数据连接。 ![22.png](https://upload-images.jianshu.io/upload_images/2904860-9f2b4eb8af7b98aa.png?imageMogr2/auto-orient/strip%7Cimage...
c# 做tcp服务器端接收数据时,无法获取发送数据
private void Listen()rn rn Socket listener = new Socket(AddressFamily.InterNetwork,rn SocketType.Stream, ProtocolType.Tcp);rn listener.Bind(new IPEndPoint(serverIP, 3588));rnrn //不断监听端口rn while (true)rn rn listener.Listen(1);rn Socket socket = listener.Accept();//监听到连接rn //Socket socket = listener.BeginAccecpt(new AsyncCallback(Accept), listener);rn //listener.BeginAccept(new AsyncCallback(AcceptCallBack), listener);//监听连接状态rnrn //while(true)rn //rn // NetworkStream ntwStream = new NetworkStream(socket);rn // StreamReader strmReader = new StreamReader(ntwStream);rn // Invoke(new PrintRecvMssgDelegate(PrintRecvMssg),rn // new object[] strmReader.ReadToEnd() );rn // listener.Listen(1);rn // socket = listener.Accept();rn //rn NetworkStream ntwStream = new NetworkStream(socket);//监听到连接rn StreamReader strmReader = new StreamReader(ntwStream);rn Invoke(new PrintRecvMssgDelegate(PrintRecvMssg), new object[] strmReader.ReadToEnd() );rn socket.Close();rn //MessageBox.Show("11");rn rn rnrn //程序的listener一直不关闭rn //listener.Close();rn rnrn这个是监听发送数据模块,只有客户端断开连接之后,数据才能读出来,在 Invoke(new PrintRecvMssgDelegate(PrintRecvMssg), new object[] strmReader.ReadToEnd() );处加了断点发现连接服务器之后程序就卡死在这里不走了,只有断开客户端程序才往下走,数据才能读出来
delphi中如何实现多线程socket通信时
delphi中实现多线程socket通信时,服务器类型置为线程方式时为何不能接收client端的消息
socket通信,客户端连续发送数据而服务器端只能收到一个,求解
目前的问题是客户端发送的是连续的数据,而服务器端只能接收到一个数据,客户端我只列出了线程的部分程序,这个问题已经困扰我几天了,在线等大神们的解答。rn服务器端程序:rn[code=java]rnpublic class TCPServer rn static int port = 9800;rn public static void main(String[] args) throws IOException rn ServerSocket ss = new ServerSocket(port);rn boolean again = true;rn while (again) rn System.out.println("TCP服务器在" + port + "等待连接...");rn Socket socket = ss.accept();rn System.out.println("客户端IP: " + socket.getInetAddress() + "端口号" + socket.getPort() + "已连接进来!!!");rn DataInputStream dInputStream = new DataInputStream(socket.getInputStream());rn //读取用户发送的数据 rn String data = dInputStream.readUTF();rn while(data != null)rn System.out.println("客户端发送的数据是: " + data);rn System.out.println("555");rn rn dInputStream.close();rn socket.close();rn ss.close();rn rn rn rn[/code]rn客户端程序:rn[code=java]rn//用Socket为服务器传送数据rn class NetThread extends Threadrn private TalkActivity talkActivity;rn public NetThread(TalkActivity talkActivity) rn this.talkActivity = talkActivity;rn rn @Overridern public void run() rn try rn final Socket socket = new Socket("192.168.0.9", 9800);rn os = socket.getOutputStream();rn pw = new PrintWriter(os);rn rn timer = new Timer();rn timer.schedule(new TimerTask() rn @Overridern public void run() rn try rn DataOutputStream dOutputStream = new DataOutputStream(socket.getOutputStream());rn dOutputStream.writeUTF(data);rn Log.i("peng", data);rn dOutputStream.flush();rn dOutputStream.close();rn rn dOutputStream.flush();rn dOutputStream.close();rn catch (Exception e) rn final String msg = e.getMessage();rn //Toast.makeText(talkActivity, msg, Toast.LENGTH_SHORT).show();rn rn rn , 100, 10); rnrn catch (Exception e) rn final String msg = e.getMessage();rn Toast.makeText(talkActivity, msg, Toast.LENGTH_SHORT).show();rn rn rn rn[/code]
C语言实现socket通信
实现客户端、服务器相互通信功能,在telnet连接localhost可以成功收发消息
C语言实现Socket通信
  服务端(server.c) #include &amp;lt;stdio.h&amp;gt; #include &amp;lt;winsock2.h&amp;gt; int main(void) {         int len = 0;         WSADATA         wd;         int ret = 0;         SOCKET s,c;         char sendBuf[...
C实现socket通信
用C语言实现socket通信的客户端和服务器,可供参考和学习
SOCKET编程中如何让服务器端按照自己定义的数据结构发送数据?
能不能给个例子,如果要开两个端口传送数据,该怎么办呢?rn多谢
线程中如何使用pDC
//首先将窗体句柄传给线程参数rnhWnd=GetSafeHwnd();rnm_pThread=AfxBeginThread(ThreadAcquireData,hWnd);//启动线程rnrn//接下来我在线程中新建CDC对象rnUINT ThreadAcquireData(LPVOID ThreadParam)rn//新线程,读取采集卡数据rn CDC* pDC=GetDC((HWND)ThreadParam); rn ......rnrnrn但是提示错误:rnerror C2440: 'initializing' : cannot convert from 'struct HDC__ *' to 'class CDC *'rn Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style castrnrn请各位英雄帮忙啊!!!!
用户消息在线程中如何使用?
我想写一个Worker Thread,在该线程完成一功能时需要通知指定窗口,让窗口完成后续工作,我想通过Worker Thread投寄一条用户消息到指定窗口,触发窗口处理程序。rn 请问如何定义、使用该用户自定义的用户消息来完成我所想的功能。rnrn 不胜感激
线程中如何使用定时器?
我作了一个网络定时发送程序,由于网络发送的时候会引起堵塞。所以,我想在辅助线程中实现,主线程作界面提示信息,不知道如何实现,在辅助线程中,不知道如何实现定时发送,请高手指教,谢谢
相关热词 c#入门推荐书 c# 解码海康数据流 c# xml的遍历循环 c# 取 查看源码没有的 c#解决高并发 委托 c#日期转化为字符串 c# 显示问号 c# 字典对象池 c#5.0 安装程序 c# 分页算法