求助,C# winform实现socket接收客户端数据,总是丢数据。

程序主体是client端发送数据给server端,server那边接收到信息就发送一条固定的确认信息给client。

出现的问题就是运行的时候会固定丢掉第二次返回的数据,第一次和其他时候的都正常。打断点调试的时候也是正常的,很懵啊。。 感觉跟UI刷新有关,却又解决不了。另开线程接收也会有这个问题。贴上代码,求助大神。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace SocketDemo_Client
{
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}

    private Socket soc_client = null;
    private byte[] socket_buf = null;
    private Thread t_listener = null;



    private void MainForm_Load(object sender, EventArgs e)
    {
        if (socket_buf == null)
        {
            socket_buf = new byte[4096];
        }
    }

    /// <summary>
    /// 连接按钮的点击事件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void btnConnect_Click(object sender, EventArgs e)
    {
        IPAddress host_ip = IPAddress.Parse(this.txtIP.Text);
        IPEndPoint end_ipe = new IPEndPoint(host_ip, Convert.ToInt32(this.txtPort.Text));
        soc_client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        soc_client.Connect(end_ipe);
        this.txtLog.AppendText("连接到" + soc_client.RemoteEndPoint.ToString() + "服务端。。。");
        this.txtLog.AppendText(System.Environment.NewLine);
    }

    private void btnDisConnect_Click(object sender, EventArgs e)
    {
        this.txtLog.AppendText("关闭双向传输通道。。。");
        this.txtLog.AppendText(System.Environment.NewLine);
        soc_client.Shutdown(SocketShutdown.Both);
        Thread.Sleep(500);
        this.txtLog.AppendText("关闭Socket对象。。。");
        this.txtLog.AppendText(System.Environment.NewLine);
        soc_client.Close();
    }

    private void btnSendMsg_Click(object sender, EventArgs e)
    {
        if (this.txtMsg.Text == "")
        {
            MessageBox.Show("输入发送内容啊骚年!");
            return;
        }
        this.txtLog.AppendText("发送" + this.txtMsg.Text + "到服务端。。。");
        this.txtLog.AppendText(System.Environment.NewLine);

        /*
        Array.Clear(socket_buf, 0, socket_buf.Length);
        socket_buf = Encoding.ASCII.GetBytes(this.txtMsg.Text);
        soc_client.Send(socket_buf);
        //清空发送框
        this.txtMsg.Text = "";

        //启动接收监听线程
        if (t_listener == null)
        {
            t_listener = new Thread(MsgListener);
            t_listener.Start();
        }
        if (t_listener.ThreadState == ThreadState.Suspended) 
        {
            t_listener.Resume();
        }
        */
        string getStr = "";
        getStr = SendAndReceive(this.txtMsg.Text);

        Thread.Sleep(2000);
        this.txtLog.AppendText("收到服务端信息:");
        this.txtLog.AppendText(System.Environment.NewLine);
        this.txtLog.AppendText(getStr);
        this.txtLog.AppendText(System.Environment.NewLine);


    }

    /// <summary>
    /// 
    /// </summary>
    private string SendAndReceive(string msg) 
    {

        Array.Clear(socket_buf, 0, socket_buf.Length);
        socket_buf = Encoding.ASCII.GetBytes(msg);
        soc_client.Send(socket_buf);
        //清空发送框
        this.txtMsg.Text = "";
        string t = "";
        soc_client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 500);
        Array.Clear(socket_buf, 0, socket_buf.Length);
        try
        {
            while (true) 
            {
                int length = soc_client.Receive(socket_buf);
                t += Encoding.ASCII.GetString(socket_buf, 0, length);
            }
        }
        catch (SocketException e) 
        {
            return t;
        }
        return t;
    }


    /// <summary>
    /// 接收线程
    /// </summary>
    private void MsgListener()
    {
        string get_str = "";
        soc_client.SetSocketOption(SocketOptionLevel.Socket,SocketOptionName.ReceiveTimeout,500);
        while (true)
        {
            Array.Clear(socket_buf, 0, socket_buf.Length);
            try
            {

                int length = soc_client.Receive(socket_buf);  //接收活动连接发送的数据填充到buffer中 
                get_str += Encoding.ASCII.GetString(socket_buf, 0, length);  //将缓存buffer的byte数据转换成字符串

            }
            catch (SocketException se)
            {
                //线程委托去刷新信息
                this.Invoke(new MethodInvoker(delegate
                {
                    this.txtLog.AppendText("收到服务端信息:");
                    this.txtLog.AppendText(System.Environment.NewLine);
                    this.txtLog.AppendText(get_str);
                    this.txtLog.AppendText(System.Environment.NewLine);
                    get_str = "";
                }));
                //挂起线程
                t_listener.Suspend();
                continue;
            }
        }
    }
}

}

3个回答

第一次是正常的,说明 你代码可运行,第二次,收不到,我觉得原因:这个问题就是网络问题,就是长连接与短连接的问题。 发送端都最好是用短连接,接收端一直监听一个端口的信息就好了

你是同一台机器调试的吗。试试局域网用两台机器调试

把发送数据的BUFFER和接收数据的BUFFER分开为两个变量试试?比如发送的是Send_buf,接收的是recieve_buf,点击按钮和接收数据线程同时都有对socket_buf的操作可能会导致问题

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
Socket 循环接收客户端数据
Socket 怎样创建监听循环接收客户端数据
socket数据接收处理问题C#
问题描述:rn在“private void btnDiagnosticClicked(object sender, EventArgs e)”方法中rn执行“RecData = MainMenu.socketHH.GetRecData();”“RecData”一直接收为空。rn而在“private void ReceiveCallback(IAsyncResult ar)”方法中rn“recBuf = new byte[byteRecLen];rn Array.Copy(state.buffer, recBuf, byteRecLen);”rnrecBuf确有数据。rn请大侠们指点。非常感谢!rnusing System;rnusing System.Collections.Generic;rnusing System.ComponentModel;rnusing System.Data;rnusing System.Drawing;rnusing System.Text;rnusing System.Windows.Forms;rnusing System.Threading;rnnamespace MenuShellrnrn public partial class DiagnosticMenu : Formrn rn ClientSocket socketHH = new ClientSocket();rn private void btnDiagnosticClicked(object sender, EventArgs e)rn rn tryrn rn socketHH.SendData(PackerHH.Send_Diagnostic());rn Thread.Sleep(210);rn byte[] RecData = null;rnrn RecData = MainMenu.socketHH.GetRecData();rnrn if (RecData != null)rn rn string transData = PackerHH.Rec_Diagnostic(RecData, RecData.Length);rn //MessageBox.Show(transData.ToString(), "btnDiagnosticClicked");rn MainMenu.socketHH.DelRecBufData();rn checklistBox.Items.Clear();rn checklistBox.Items.Add(transData);rn rn elsern rn MessageBox.Show("is null");rn rn rn catch (Exception ex)rn rn MessageBox.Show("Diagnostic error:" + ex.ToString());rn rn rnrn rn rnrnusing System;rnusing System.Collections.Generic;rnusing System.Text;rnusing System.Net.Sockets;rnusing System.Net;rnusing System.Windows.Forms;rnusing System.Threading;rnusing System.Diagnostics;rnusing System.IO;rnrnnamespace MenuShellrnrn public class ClientSocketrn rn private string hostIP; //服务器ip地址rn private int hostPort = 0; //服务器端口rn private IPEndPoint endIP;rn private Socket csocket = null;rn private Thread delTh = null; //开启一个线程删除超时内存内容rn private Thread socketConnTh = null;rn private byte[] recBuf = null;rn private byte[] recBufHH = null;rn private byte[] byteHH = 0x7E, 0x04, 0x04 ;rn private ManualResetEvent connectDone = new ManualResetEvent(false);rn private ManualResetEvent sendDone = new ManualResetEvent(false);rnrn public void CreateSocket(string ip, int port)rn rn hostIP = ip;rn hostPort = port;rn IPAddress addIP = IPAddress.Parse(hostIP);rn endIP = new IPEndPoint(addIP, hostPort);rn if (csocket == null)rn rn SocketConn();rn rn rn private void SocketConn()rn rn tryrn rn if (csocket == null)rn rn csocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);rn connectDone.Reset(); //允许一个或多个等待线程继续rn csocket.BeginConnect(endIP, new AsyncCallback(ConnectCallback), csocket);rn connectDone.WaitOne(); //阻止当前线程,直到当前的 WaitHandle 收到信号rn rn rn catch (Exception e)rn rn new ApplicationException(e.Message);rn rnrn rn private void ConnectCallback(IAsyncResult ar)rn rn tryrn rn Socket client = (Socket)ar.AsyncState;rn client.EndConnect(ar); //结束挂起的异步连接请求rn if (hostPort != 0) //zjl --add 20091012rn rn RecieveData();rn //RecDataThread();rn DelBufThread();rn rnrn rn catch (Exception e)rn rn new ApplicationException(e.Message);rn rn finallyrn rn connectDone.Set();rn rn rn //Socket连接服务线程rn private void SocketConnThread()rn rn socketConnTh = new Thread(new ThreadStart(SocketConn));rn socketConnTh.Start();rn rnrn public bool SendData(byte[] sendByte)rn rn tryrn rn // MessageBox.Show(sendByte.Length.ToString() + " 发送信息 " + Encoding.ASCII.GetString(sendByte, 0, sendByte.Length));rn if ((sendByte != null) && (csocket.Connected))rn rn csocket.BeginSend(sendByte, 0, sendByte.Length, 0, (new AsyncCallback(SendCallback)), csocket);rn return sendDone.WaitOne();rn rn return false;rn rn catch (Exception e)rn rn new ApplicationException(e.Message);rn return false;rn rn rn private void SendCallback(IAsyncResult ar)rn rn tryrn rn Socket client = (Socket)ar.AsyncState;rn client.EndSend(ar);rn rn catch (Exception e)rn rn new ApplicationException(e.Message);rn rn finallyrn rn sendDone.Set();rn rn rnrn //--------------接收数据--------------rn private void RecieveData()rn rn tryrn rn StateObject state = new StateObject();rn state.worksocket = csocket;rn if (csocket != null)rn rn csocket.BeginReceive(state.buffer, 0, state.GetBufSize(), 0, new AsyncCallback(ReceiveCallback), state);rn rnrn rnrn catch (Exception e)rn rn MessageBox.Show("接收数据异常:" + e.Message);rn rnrn rn //---------接收回调函数--------rn private void ReceiveCallback(IAsyncResult ar)rn rn tryrn rn StateObject state = (StateObject)ar.AsyncState;rn Socket client = state.worksocket;rn int byteRecLen = 0;rn byteRecLen = client.EndReceive(ar);rn if (byteRecLen > 0)rn rn switch (hostPort)rn rn case 8000:rn recBuf = new byte[byteRecLen];rn Array.Copy(state.buffer, recBuf, byteRecLen);rn break;rn case 7000:rn recBuf = new byte[byteRecLen];rn Array.Copy(state.buffer, recBuf, byteRecLen);rn break;rn case 5000:rn if (((state.buffer[0] == byteHH[0]) && (state.buffer[1] == byteHH[1])) && (state.buffer[2] == byteHH[2]))rn rn recBufHH = new byte[byteRecLen];rn Array.Copy(state.buffer, recBufHH, byteRecLen);rn rn elsern rn recBuf = new byte[byteRecLen];rn Array.Copy(state.buffer, recBuf, byteRecLen);rn rn break;rn default:rn break;rn rn rn if (client.Connected == true)rn rn client.BeginReceive(state.buffer, 0, state.GetBufSize(), 0, new AsyncCallback(ReceiveCallback), state);rn rn elsern rn MessageBox.Show(" client.Connected = " + client.Connected.ToString());rn rnrn rn catch (Exception e)rn rn new ApplicationException(e.Message);rn rn rn //--------------向外传递数据--------------rn public byte[] GetRecData()rn rn return recBuf;rn rnrn public byte[] GetRecDataHH()rn rn return recBufHH;rn rnrn public void DelRecBufData()rn rn if (recBuf != null)rn rn Thread.Sleep(300);rn recBuf = null;rn rn rnrn public void DelRecBufDataHH()rn rn if (recBufHH != null)rn rn Thread.Sleep(300);rn recBufHH = null;rn rn rn //--------------清除recBuf信息线程--------------rn private void DelBufThread()rn rn delTh = new Thread(new ThreadStart(DelBufData));rn delTh.Start();rn rn //--------------每隔5000毫秒清楚一次recBuf信息--------------rn private void DelBufData()rn rn while (true)rn rn Thread.Sleep(50000);rn if (recBuf != null)rn rn //MessageBox.Show("5秒时间到,删除数据");rn recBuf = null;rn rn if (recBufHH != null)rn rn //MessageBox.Show("5秒时间到,删除数据");rn recBufHH = null;rn rn rnrn rn rnrn
Socket 发送 接收 数据 c#
Socket 发送 接收 数据 c#Socket 发送 接收 数据 c#
为什么socket控件接收的数据总是不正确???
我用vb6编程,使用socket控件建立了c/s程序。但我发现,在传输少量数据时,传输是正确的,一点问题都没有。但是当我的服务器发送大量数据时,客户端程序接收了一部分数据后就不正常了,似乎是大量的数据发送导致了客户端的数据接收缓冲区紊乱,如何解决这个问题已经困扰了我很久。rn 我以为,解决这个问题一种办法是增大数据接收缓冲区,但我不知该如何操作;另一种办法是改善数据接收的效率——发的快只要接收的也快不就没有问题了吗!?rn 不知哪为高手能给我指出问题的根本所在,必有重谢!!!rnrn 2001.11.17rnrnoicq: 40501389rnemail: alanghd@263.netrn
急!socket 客户端数据接收失败
我写了个Windows(Server)-Linux(Client)间socket通信的程序,Server端起来后,再起Client,Client发送的数据Server能收到,但是Server发送的数据,Client收不到。rnrn 后用netstat -A inetrn[abc@server Client]$ netstat -A inetrnActive Internet connections (w/o servers)rnProto Recv-Q Send-Q Local Address Foreign Address State rntcp 3950 0 localhost:55921 localhost:45000 ESTABLISHEDrn[abc@server Client]$ netstat -A inetrnActive Internet connections (w/o servers)rnProto Recv-Q Send-Q Local Address Foreign Address State rntcp 3990 0 localhost:55921 localhost:45000 ESTABLISHEDrnrn从Recv-Q看,Client主机已经收到了数据(每次Server都会发40字节的数据给Client),但是我的程序却没有接收到数据。rn很纠结,不知道什么原因。rnrn同时在程序里,我打出了Client的socket端口和地址,居然都是0,很迷惑,还请高手指教!!!
linux socket服务器异步接收客户端数据
服务器程序使用linux c编写的,客户端使用Windows下的C#语言,在服务器中使用signal(SIGIO,handler)异步方式来接收客户端的请求,但是只有客户端的“连接请求”信号才能触发SIGIO信号,才能进入到handler处理函数中,其他来自客户端的数据请求不能触发SIGIO信号,因此也不能进入信号处理函数handler中,(也就是只能与客户端进行“握手”,不能接收到客户端的其他数据请求)。不知道跟signal函数有关还是跟SIGIO信号有关?请各位大神赐教,或者还有没有更好的办法rn下面是服务器的代码:rn/******************************************************************************rn* @attentionrn* rn* (c) Copyright 2015, Nanjing Kangni Mechanical & Electrical Co., Ltd.. All Rights Reserved.rn*rn*******************************************************************************rn* @Filename DSSCtrl.crn* @Author zhoujbrn* @Date 2015-11-16rn* @Version V001-000rn* @Descriptionrn* @Function Listrn* 1. .... rn*******************************************************************************rn* @Historyrn* 1. zhoujbrn* zhoujb, V001-000, 2015-11-16rn******************************************************************************/rnrn/******************************************************************************rn* Includesrn******************************************************************************/rn#include rn#include rn#include rn#include rn#include rn#include rn#include rn#include rn#include rn#include rn#include rn#include rn#include rn#include rn#include rn#include rn#include rn#include rn#include rn#include rn#include rn#include rnrn/******************************************************************************rn* Private macrorn******************************************************************************/rn#define PORT 4321rn#define BUFFER_SIZE 1024rn#define MAX_QUE_CONN_NM 5rn#define SEND_SIZE 1024rnrn/******************************************************************************rn* Private variablesrn******************************************************************************/rnrnrnstruct sockaddr_in server_sockaddr, client_sockaddr;rnint sin_size, recvbytes, sendbytes;rnint sockfd, client_fd;rnchar buf[BUFFER_SIZE];rnchar wuf[BUFFER_SIZE];rnrn/******************************************************************************rn* @Name accept_async()rn* @Description Async Handler of Signalrn* @Parametersrn* @Returnrn* @Historyrn* 1. Creatern* zhoujb, V001-000, 2015-12-2rn******************************************************************************/rnvoid accept_async(int sig_num)rnrn int i=0;rn sin_size = sizeof(client_sockaddr);rn rn printf("trying to connect\n");rn rn if((client_fd = accept(sockfd, (struct sockaddr *)&client_sockaddr, &sin_size)) == -1)rn rn perror("accept");rn exit(1);rn rn memset(buf, 0, sizeof(buf));rn rn if((recvbytes = recv(client_fd, buf, BUFFER_SIZE, 0)) == -1)rn rn perror("recv");rn exit(1);rn rn rn printf("Received a message: %d\n", buf[0]);rn rn if(buf[0] == 0x01)rn rnrn if(sendbytes = send(client_fd, buf, 1, 0) == -1)rn rn perror("send");rn exit(1);rn rn printf("hand shake sucessfully!\n");rnrn rn rn if(buf[0] ==0x02)rn rn if(sendbytes = send(client_fd, buf, 1, 0) == -1)rn rn perror("send");rn exit(1);rn rn printf("send sucessfully !\n");rn rn rn rn if(buf[0] == 3)rn rn while(1)rn rn sleep(1);rn if(sendbytes = send(client_fd, buf, 1, 0) == -1)rn rn perror("send");rn exit(1);rn rn i++;rn printf("send times is :%d ,buf is :%d\n",i,buf[0]);rn rn rn if(buf[0] == 4)rn rn printf("stop sending message!\n");rn exit(1);rn rn rnrnrn/******************************************************************************rn* Public functionsrn******************************************************************************/rnrn/******************************************************************************rn* @Name mainrn* @Description main taskrn* @Parametersrn* @Returnrn* @Historyrn* 1. Creatern* zhoujb, V001-000, 2015-11-23rn******************************************************************************/rnint main(int argc, char *argv[])rnrn int flags;rnrn rn if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)rn rn perror("socket");rn exit(1);rn rn printf("Socket id = %d\n", sockfd);rnrn server_sockaddr.sin_family = AF_INET;rn server_sockaddr.sin_port = htons(PORT);rn server_sockaddr.sin_addr.s_addr = INADDR_ANY;rn bzero(&(server_sockaddr.sin_zero), 8);rnrn int i = 1;rn setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));rnrn if(bind(sockfd, (struct sockaddr *)&server_sockaddr, sizeof(struct sockaddr)) == -1)rn rn perror("bind");rn exit(1);rn rn printf("Bind success!\n");rnrn if(listen(sockfd, MAX_QUE_CONN_NM) == -1)rn rn perror("listen");rn exit(1);rn rn printf("Listening........\n");rn signal(SIGIO, accept_async);rn fcntl(sockfd, F_SETOWN, getpid());rn flags = fcntl(sockfd, F_GETFL);rnrn if(flags < 0 || fcntl(sockfd, F_SETFL, flags | O_ASYNC) < 0)rn rn perror("funtl");rn rn rn while(1)rn rn sleep(2);rn printf("the task is working....\n"); rn rn rn close(sockfd);rn exit(0);rn exit(EXIT_SUCCESS); rn rn rn
MFC SOCKET 接收机械臂实时数据客户端
这是我在做项目之初做的一个简单的底层数据接收的代码,有数据解析,基于VS2010开发的,希望对初学者有一定帮助。
客户端接收socket数据不正确,求解
如图出现的错误情况。客户端接收这样的数据,。。。[img=https://img-bbs.csdn.net/upload/201512/08/1449535137_933362.png][/img]
Python入门:socket连续接收客户端数据
from socketserver import ThreadingMixIn,ForkingMixIn,StreamRequestHandler import socket,selects = socket.socket() #host = socket.gethostname() host = '127.0.0.1' print(host) port = 8088 s.bind((host,po
WinForm接收ArrayBuffer数据
现有一接口数据返回类型为ArrayBuffer,请问在winform中应该以什么类型接收如何解析?rn[img=https://forum.csdn.net/PointForum/ui/scripts/csdn/Plugin/003/onion/10.gif][/img]
socket数据接收乱码问题
各位大虾急救,问题是这样的。rn我这边做了个数据接收socket客户端,编码格式是GBK,服务器端是GB2312,接收的其他数据都是正常的,现在出现了一个子“珺”,当数据六种出现这个字时就会成乱码,变成“?”,请问有什么办法解决,先谢过了
socket数据的接收和发送
Linux下数据的接收和发送 Linux 不区分套接字文件和普通文件,使用 write() 可以向套接字中写入数据,使用 read() 可以从套接字中读取数据。 前面我们说过,两台计算机之间的通信相当于两个套接字之间的通信,在服务器端用 write() 向套接字写入数据,客户端就能收到,然后再使用 read() 从套接字中读取出来,就完成了一次通信。 write() 的原型为: s
socket数据接收问题。
server和client建立连接后,一方是如何知道另一方发送了数据?总不能不停的循环recv吧,这样如果大部分时间都没有通讯就太浪费cpu资源了。rnrn另外还有个一直想不通的问题,当一方发现有数据开始receive时,怎么知道发送方已经把要发送的数据都发过来了?rn举个例子,A向B发送一句话有20个字符,B从缓冲区中读数据时,可能由于网速原因只读到12个字符,B会以为A只发送了12个字符。过了一段时间,剩下的8个字符到达B的缓冲区,B以为A又发送了一句8个字符的话。怎么解决这个问题?rnrn不知道我说清楚了没有?
socket的数据接收问题
TCP协议,假设客户端发送了1024个字节过来,服务端这边把接收长度设成1024,有没有可能实际一次收到的字节数小于1024?rn谢谢
socket的数据接收问题?
ServerSocket发送数据[堵塞方式]rn如果我有一个服务器和多个客户端,我想在服务器发送数据给某一个客户端。rn//目前采用serversock1.socket.connect[0].sendtext('read');rn ^这个值不知怎么修改rn请问套间字应该怎样设置。rnrn如果有线程方式的实现就更好了。
Socket 数据接收的问题..
用TServerSocket做了个Socket Server,一直工作正常.rn最近遇到一个很奇怪的问题,请高手指点下.rnrn现在Socket 接收的是两种数据,一种是实时数据,一种是历史数据.rn实时数据和历史数据的差别就在于实时数据是两条记录,历史记录只有一条记录,但实时数据rn的第二条记录格式与历史记录一模一样.rnrnSocket 接收实时数据时,不管压力多大,都能正常接受.但接受历史数据时,接收到600多条记录的时候就要报错.现在把接收历史数据的后期处理函数都注释掉.rn只在TServerSocket的OnClientRead事件中用Socket->ReceiveBuf来接收.但还是要报出Socket error 10038 - Socket operation on non-socket .rn非常不解..请高手指点...rn
Socket 接收广播数据
一台PC(PC),与一台Philips心电监视设备Monitorrn1)PC 每隔2秒发送一次请求给——〉Monitorrn2)PC端另外创建一个Socket(sock)接收广播的数据,但是当sock.Receive(by)时,不进行了 请各位高手,指点同时给一些接收硬件广播的例子谢谢!!rn注:发送与接收创建了两个不同的socket。rn接收:rn System.IO.FileStream fs = null; rnEndPoint mip = (EndPoint)new IPEndPoint(IPAddress.Parse("192.168.1.103"), 7100);rnSocket sRec = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);rnsRec.Bind(mip);rnwhile (true)rnrn byte[] by = new byte[1024];rn int Rcount = 0; rn Rcount = sRec.Receive(by); //此处停留rn if (Rcount > 0)rn rn fs = new FileStream("c:\\aa.dat", FileMode.Append, FileAccess.Write);rn fs.Write(by, 0, Rcount);rn fs.Close();rn rn rn
SOCKET 数据接收与缓存?
写了一个TCP 的小程序 ,在另一端是接收的,需要把接收的数据写入到硬盘,但是不想每次都写,想把这些接收到的数据按顺序放到一个地方,等到一定大小之后再写。rnrn大家给点意见,谢谢了。
socket数据接收不全
如题。TCP传输时,由于接收的数据包比较大,定义了一个2300字节长度的包,但是每次监听接收到的包都不完全,而且每次都还自动连续重复接收两三次,第一次有包头,第二次没包头的那种。。。。。,下面的代码写的不合适吗?怎么样让它接收完全呢。rn Socket socket;rn Socket newSocket; rn private static byte[] byteScouse = new byte[2300];rn private void BeginListen()rn rn IPEndPoint iep = new IPEndPoint(IPAddress.Any, 8000);rn rn socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);rn rn socket.Bind(iep);rn socket.Listen(500);rn newSocket = socket.Accept(); rn rn while (true)rn rn newSocket.Receive(byteScouse); rn rn newSocket.Shutdown(SocketShutdown.Both);rn newSocket.Close();rn rn rn
socket 接收图片数据
int RecvImageData(SOCKET socket,char *pImageData,int ImageSize) { int nCount = 0; int nRet = 0; while (nCount { nRet = ::recv(socket, (char *)pImageData + nCount, ImageSize - nCount, 0); i
关于socket数据接收
序列化后的字节流sendBuf=(length+数据内容),其中length表示数据内容的长度,固定用8个字节表示(如00001254表示数据内容长为1254),请问可以发送sendBuf么?还是要申请一块内存出来然后把数据拷贝进去呢?rnrn 还有就是接收方面recvBuf,网上都说先接收数据长度,然后再接收数据,但是具体在代码上该如何实现先接收前8位字节得到数据内容的长度,然后接收数据内容并判断数据接收完成呢?rn rn 网上有一些这方面的例子,但是大神们的例子对我这个菜鸟来说确实有点难懂,哪位兄弟能给个比较简单的实例么,麻烦了!!
socket数据接收控制
想实现如下功能,若对方发送数据,则recv()接收数据,将接收的数据打印出来,否则,不执行打印,用c语言怎样实现?接收数据的函数是一个单独的线程。有什么可以判断对方是否发送了数据吗?谢谢。rn如果recv接收到了数据,则printf,否则,不执行。rnrecv(s,buf,sizeof(buf),0);rn rnprintf("service say:%s\n",buf);
socket 数据接收与缓存?
写了一个tcp 的小程序 ,在另一端是接收的,需要把接收的数据写入到硬盘,但是不想每次都写,想把这些接收到的数据按顺序放到一个临时缓冲区,等全部接收完后再写!!!rn大家给点意见,谢谢了!!!
客户端与服务器端数据接收
服务器端:连续发送 3笔数据rn _clientSkt.Send(new byte[] 9, 2 );rn _clientSkt.Send(new byte[] 9, 1 );rn _clientSkt.Send(_msgBuff);rn客户端: rn byte[] buf = new byte[_maxPacket];rn int byteCnt = _nws.Read(buf, 0, buf.Length);rn byte[] buf 1= new byte[_maxPacket];rn int byteCnt 1= _nws.Read(buf1, 0, buf1.Length);rn byte[] _msgBuff = new byte[_maxPacket];rn _nws.Read(_msgBuff, 0, _msgBuff.Length);rnrn发现在客户端的_msgBuff 有时候能获取到数据,有时候却不能,求大神们指教
丢数据
对于任何存储,丢失数据后,不管是没找到原因,或者没找到解决方案,都是无法过用户这一关的。 今天上午因为meta表损坏丢失了数据,虽然即将开发完成恢复meta表的工具,但是没找到原因很痛苦啊...
c#客户端SOCKET接收中文乱码
[size=16px]serverrn是c++写的执行sql语句从oracle数据库中查询内容通过socket发送;c++编译默认编码是unicode[/size]rn[code=c]rn_RecordsetPtr Rp=connect.GetRecordset(sql);rn_variant_t varUserName;rnstring strUserName;rnvarUserName = Rp->GetCollect ("TICKETCODE");//票号rnstrUserName=strUserName+(char *)_bstr_t(varUserName);rnstrUserName=rtrim(strUserName);rnsend(clientSocket,strUserName.c_str(),strUserName.length(),0);rn[/code]rn[size=16px]rnclient:rnc++写的windows窗体应用程序客户端接收不会乱码;rn是c#写的WP客户端接收以后乱码 相关代码如下;[/size]rn[code=csharp]rnstring response = "something";rnSocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();rnsocketEventArg.RemoteEndPoint = _socket.RemoteEndPoint;rnsocketEventArg.SetBuffer(new Byte[MAX_BUFFER_SIZE], 0, MAX_BUFFER_SIZE);rnsocketEventArg.Completed += new EventHandler(delegate(object s, SocketAsyncEventArgs e)rnresponse = Encoding.UTF8.GetString(e.Buffer, e.Offset, e.BytesTransferred);//个人猜测是这里设置编码有问题rnresponse = response.Trim('\0');[/code]rn[size=16px]改成如下代码也不行[/size]rn[code=csharp]rnresponse = Encoding.unicode.GetString(e.Buffer, e.Offset, e.BytesTransferred);[/code]rn[size=16px]求助啊啊啊[/size]
基于C# Winform的串口数据接收
很多初学者在接触到串口编程时,不知道如何入手,找了网上一些文章,也是鱼龙混杂,不好学习。 今天,我分享一篇文章,讲述 基于C# Winform的串口数据接收编程(适合大概明白WinForm编程的同学,没有接触过WinForm的同学下载源码学习)
C#导入EXCEL丢数据
C#导入EXCEL丢数据,如0000为0,002100为2100,前加"'"可解决,不加可不可解决,建立EXCEL对象时,可不可把整个工作薄单元格设为文本
C# socket接收单片机数据问题
单片机通过wifi将采集到传感器的数据传至上位机,单片机是每一秒发送一组数据,如“0xaa,0x55,‘采集到的数据1’,‘采集到的数据2’”rn问:怎样才能接收数据并判断第一个是“0xaa“并且第二位是”0x55“时候将”采集到的数据1“和”采集到的数据2“拿出来并整合合,下一秒也是这样循环下去,我现在只能做到接收数据。rnprivate byte[] m_receiveBuffer = new byte[1024];rnsock.BeginReceive(m_receiveBuffer, 0, m_receiveBuffer.Length, 0, new AsyncCallback(ReceiveCallBack), null);rnprivate void ReceiveCallBack(IAsyncResult ar)rn rn tryrn rn int REnd = sock.EndReceive(ar);rn rnrn string strReceiveData = m_receiveBuffer[0].ToString("X2");rn this.HandleMessage(strReceiveData);rn sock.BeginReceive(m_receiveBuffer, 0, m_receiveBuffer.Length, 0, new AsyncCallback(ReceiveCallBack), null);rn rn rn catch (Exception ex)rn rn throw new Exception(ex.Message);rn rn rnprivate void HandleMessage(string message)rn rn message = message.Replace("\0", "");rn if (!string.IsNullOrEmpty(message))rn rn label6.Text = message;rn rn rn
C# 使用Socket发送和接收TCP数据
C# 使用Socket发送和接收TCP数据,包含客户端和服务器端,发送Send,监听Listen ,C#运行环境VS2010
C# socket接收十六进制数据,求帮助!!
FF FF FF 2 0 0 1D 3 0 1 0 0 0 0 0 0 0 0 0 40 数据大概就是这种格式,FF FF FF是开头,是一个byte[19]的数组,这个数据发送过来的时候,C#在接收的时候,单个的0会不会影响数据接收的格式??????rnrn3个FF后,前3个字节,代表一个数据,然后是1个字节,然后是2个字节,1个字节,最后一堆就不用管了。rnrn我在接收的时候是不是应该这么写?rnrn[code=csharp]rnwhile (true) rn byte[] b2 = new byte[2]; //先用3个字节来判断FF FF FFrn int r = socket1.Receive(b2,b2.Length,0);rn if(r == 0)rn continue ;rn rn if(Encoding .ASCII .GetString (b2,0,r) != "FFFFFF") //如果找到3个FF 就开始找后面的17个字节rn break ;rn elsern byte[] b3 = new byte[16];rn int rs = socket1.Receive (b3,b3.Length ,0); //这个接收会不会影响我下面写的数据转换???rn if(rs == 0)rn continue ;rn rn string dingwei = b3[2].ToString("X2") + b3[1].ToString("X2") + b3[0].ToString("X2") ; //这是开始的前3个rn string speed = b3[3].ToString("X2"); rn string angle = b3[5].ToString("X2")+ b3[4].ToString("X2");rn string fx = b3[6].ToString("X2");rn rnrnrn[/code]rnrn我这样写可以得到数据中的十六进制数据吗??????求大神帮我看一下 谢谢了!~!!rnrn
C# SOCKET直接接收16进制数据
我用C#写的客户端,接收从POS机端发送过来的16进制报文,用byte方式接收,接收过来后,变成了10进制rn报文里还缺少了不少的0,我想是不是可以直接接收过来就是16进制?这个要怎么做?因为我用10进制转换,里面已经丢失了部分数据,转换后的16进制,和原始报文已经部分不一致。rn我的代码如下:rnconst int BufferSize = 8192; // 缓存大小,8192字节rn rn Console.WriteLine("Server is running ... ");rn IPAddress ip = IPAddress.Parse(ConfigurationManager.AppSettings["ServerIP"]);rn TcpListener listener = new TcpListener(ip,Convert.ToInt32(ConfigurationManager.AppSettings["ServerPort"]));rnrn listener.Start(); //开始监听rn Console.WriteLine("Start Listening...");rnrn while (true)rn rn // 获取一个连接,同步方法rn TcpClient remoteClient = listener.AcceptTcpClient();rn // 打印连接到的客户端信息rn Console.WriteLine("Client Connected!0 <-- 1",rn remoteClient.Client.LocalEndPoint, remoteClient.Client.RemoteEndPoint);rnrn // 获得流,并写入buffer中rn NetworkStream streamToClient = remoteClient.GetStream();rn byte[] buffer = new byte[BufferSize];rn int bytesRead = streamToClient.Read(buffer, 0, BufferSize);rn Console.WriteLine("Reading data, 0 bytes ...", bytesRead);rnrnrn // 获得请求的字符串rn //string msg = Encoding.UTF8.GetString(buffer);rn string msg = string.Empty;rn string msg2 = string.Empty;rn Console.Write("Receved:");rnrn //报文全部转换成16进制rn for (int i = 0; i < bytesRead; i++)rn rn msg += buffer[i];rn //Console.Write("0", buffer[i]);rn rnmsg = t2h(msg);rn//10进制转16进制rn static string t2h(string src)rn rn /*src = src.Replace("0","00");rn string src2 = string.Empty;rn for (int i = 0; i < src.Length; i++)rn rn if (i % 2 != 0) continue;rn if (src.Substring(i, 2) != "00")rn rn if (Convert.ToUInt32(src.Substring(i, 2)) >= 10)rn rn src2 += Convert.ToString(Convert.ToUInt32(src.Substring(i, 2)), 16);rn rn elsern rn src2 += "0" + Convert.ToString(Convert.ToUInt32(src.Substring(i, 2)), 16);rn rn rn elsern rn src2 += "00";rn rn rn return src2;*/rn string src2 = string.Empty;rn for (int i = 0; i < src.Length; i++)rn rn if (i % 2 != 0) continue;rn src2 += Convert.ToString(Convert.ToInt32(src.Substring(i,2)),16);rn rn return src2;rn
异步客户端SOCKET怎么实现不停的接收服务器端发送的数据?
Socket初学者请教各位老鸟:rn我有一个需求,服务器端Socket在11000监听,当客户端连接上服务器端以后,服务器端开始向客户端发送心跳帧,心跳帧的频率是5秒,双方通过心跳帧确立连接有效。rn连接确立后,服务器端开始向客户端发送数据,客户端收到数据后立即向服务器端返回收到的数据,服务器端收到客户端返回的刚才发送的数据后即可认为客户端已经收到这条数据,即开始发送下一条数据,否则重复发送上一条数据,在这个过程中若10秒钟内没有收到心跳帧,则认为连接已经中断。rn服务器端的程序是另一方提前开发好的,现在需要建立客户端。rn我的思路是使用异步SOCKET,因为在同步方式试验中发现,由于心跳帧的时间较短,如果用同步SOCKET则阻塞的时间会超时。rn现在的问题是我对程序架构没有清晰的思路:rn1、客户端如何不停的接收服务器端发送的数据?rn我在MSDN示例代码上加了个While,提示我“您的主机中的软件放弃了一个已建立的连接”rnWhile (true)rn rn // Send test data to the remote device.rn Send(client, "This is a Client!!!");rn sendDone.WaitOne();rnrn // Receive the response from the remote device.rn Receive(client);rn receiveDone.WaitOne();rnrn // Write the response to the console.rn Console.WriteLine("Response received : 0", response);rnrn rn2、怎样实现5秒钟的心跳帧发送频率?rn3、怎样实现客户端发送心跳帧的过程中检测服务器心跳帧的返回,若超过10秒没有收到,则重新连接Socket?
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为什么客户端收不到数据呢?
急! socket 客户端接收大于10K的数据,接收不完整
我对socket不熟悉,但是这个事挺急,请各位帮我看看。谢谢了啊 ,分不够再加!!!rnrnsocket 向服务端请求数据,返回的数据如果小于10K,那么能看到xml的整个完整的格式如下:rnrnrn rn rn ....rn rn .....rnrnrnrn如果大于10K,XML就不完整了,解析出来少了一部分,反正看不到结尾的节点.... 换成循环读取貌似也是一样。。客户端代码如下:rnrnrn[code=java]rnrnpublic String buildSocket4Sync(SocketConn sm, HostVO address, String cmd)rn rn BufferedReader br = null;rn InputStream in = null;rn String result = "";rn tryrn rn socket = new Socket(address.getIp(), address.getPort());rn OutputStream socketOut = socket.getOutputStream();rn socketOut.write(cmd.getBytes());rn socketOut.write("\r\n".getBytes());rnrn in = socket.getInputStream();rn br = new BufferedReader(new InputStreamReader(in, "utf-8"));rn String re;rn StringBuffer sbf = new StringBuffer();rn while ((re = br.readLine()) != null)rn rn sbf.append(re);rn rnrn if (sbf.length() != 0)rn rn result = new String(Base64.decode(sbf.toString()), "utf-8");rn // System.out.println(result);rnrn rnrn rn catch (IOException e)rn rn e.printStackTrace();rn rn finallyrn rn tryrn rn if (null != br)rn rn br.close();rn rn in.close();rn rn catch (IOException e)rn rn e.printStackTrace();rn rn rn return result;rn rnrn[/code]rnrn急啊,感谢感谢!
多线程的socket 客户端 总是接收不到
客户端是一个dll,程序通过多线程调用dll里的函数向服务器发送数据,rn现在发现 线程只有一个 偶尔有两个返回调用成功,其它的在接收数据的时候就发生错误了,但是数据已经都发出去了 。rnrn SOCKET fSocket::Connect(char *szIP,UINT nPort)rn rn SOCKET hSocket = INVALID_SOCKET;rn clock_t start,ends;rnrn //没有初始化,则要重新初始化rn if (!m_SocketInstalled ) return INVALID_SOCKET;rnrn rn //测试网络是否畅通rn if (!Ping(szIP))rn rn TRACE(_T("Ping failed\n"));rn closesocket(hSocket);rnrn hSocket = INVALID_SOCKET;rn return hSocket;rn rn start = clock();rn ends = clock();rn //创建SOCKETrn while ((hSocket == INVALID_SOCKET) && ((ends - start) 0 && ((tmEnd - tmStart) >= m_szTimeOut))rn rn// rnrn [color=#FF0000]TRACE(_T("Recv select = 0 ")); [/color]rn rn DisConnect(hSocket);rn rn return false;rn rn else continue;rn rnrn if (FD_ISSET(hSocket, &fds))rn rn nRet = ::recv(hSocket,(char *)lpData+nLen,nSize-nLen,0);rn if (nRet == SOCKET_ERROR)rn rn rnrn TRACE(_T("recv = SOCKET_ERROR"+ str));rnrn rnrn return false;rn rnrn nLen += nRet;rn rn rnrn return true;rnrnrnrnrnrnrn其它的线程总是 提示 Recv select = 0 rn服务器端显示 要发送多少数据 已经发送0 。rn对 c++不太懂 ,大家帮帮忙 rn
winsock 接收文件后丢数据
在本机做两个表单,一个发,一个收,收到后字节数减少。使用TcpIP 协议。rnrn发的过程是:从文件中读一段发一段,直到结束。
串口接收时丢数据问题解决方案
老规矩,先说下问题:串口在接收pc端发来的数据时(100个bytes,每200ms发送一次),偶尔会丢一些数据。某一次的测试记录如下: 第一次丢数据 发送总量60多万字节 丢了27个 第二次丢数据 发送总量80多万字节 (在上一次发送的基础上又)丢了40个 第三次丢数据 发送总量190多万字节 (在上一次发送的基础上又)丢了37个 以上数...
socket客户端连接mina客户端,发送频率过快,导致socket客户端,丢数据
tcp 协议为可靠协议,有任何问题,都是自己业务处理逻辑的原因  开发中遇到的问题:                  1.socket客户端发送数据过快,服务器未接收到。设置发送缓冲区socket.setSendBufferSize(1024*3);本人也不明白原理,但是这样确实得到解决                  2.mina数据发送过快,导致socket客户端丢数据 测试工...
使用freertos 串口接收丢数据
这个问题让调了将近两天的时间,终于解决,还是有一点成就感的。我犯的这个错误可能也是好多操作系统初学者比较容易犯的错误,在此做一下总结,希望在以后的工作中遇到同样问题的小伙伴能尽快解决。 背景:以前程序无操作系统,可实现设备的远程升级。最近将程序加入了freertos操作系统,出现远程升级包出现丢数据的情况。每包数据为544个字节。先说一下相关的系统设置: 1、中断优先级的设置NVIC_Prio...
相关热词 c# 标准差 计算 c#siki第五季 c#入门推荐书 c# 解码海康数据流 c# xml的遍历循环 c# 取 查看源码没有的 c#解决高并发 委托 c#日期转化为字符串 c# 显示问号 c# 字典对象池