慎左 2018-09-30 03:43 采纳率: 0%
浏览 2419

求助,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条回答 默认 最新

  • qiuzhihzy123 2018-09-30 09:08
    关注

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

    评论

报告相同问题?

悬赏问题

  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)