hk2540 2016-03-31 01:47
浏览 917

用c# 写的一个tcp client 发一个指令再读硬件发回来的数据,无法读取

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

namespace tongbu
{
public partial class Form1 : Form
{
string sendString = null;//要发送的字符串
byte[] sendData = null;//要发送的字节数组
TcpClient client = new TcpClient();//实例化TcpClient
NetworkStream stream = null;//网络流

    IPAddress remoteIP = IPAddress.Parse("10.104.10.10");//远程主机IP
    int remotePort = 10940;//远程主机端口

    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        try
        {
            client.Connect(remoteIP, remotePort);//连接远程主机
        }
        catch (System.Exception ex)
        {
            Console.WriteLine("连接超时,服务器没有响应!");//连接失败
            Console.ReadKey();
            return;
        }
    }

    private void button2_Click(object sender, EventArgs e)
    {
        sendString = textBox1.Text.ToString()+"\r"; //获取要发送的字符串
        sendData = Encoding.ASCII.GetBytes(sendString);//获取要发送的字节数组
        stream = client.GetStream();//获取网络流
        stream.Write(sendData, 0, sendData.Length);//将数据写入网络流
        Thread.Sleep(10);
        textBox1.Clear();

        Byte[] data3 = new Byte[client.ReceiveBufferSize];
        Int32 bytes = stream.Read(data3, 0, data3.Length);
        string responseData = System.Text.Encoding.ASCII.GetString(data3, 0, bytes);
        listBox1.Text = responseData;


        //string sss = "";
        //for (int i = 0; i < data3.Length; i++)
        //{
        //    sss += data3[i].ToString();
        //}
        //listBox1.Text = sss;

        //Thread.Sleep(10); //这个地方加上就能获取到数据,如果去掉大部分时候都不能获取到,只有少数时候能取得
        //byte[] bytes = new byte[client.ReceiveBufferSize];
        //stream.Read(bytes, 0, (int)client.ReceiveBufferSize);
        //string returndata = Encoding.ASCII.GetString(bytes);
        //returndata = returndata.Substring(0, returndata.IndexOf('\0'));
        //listBox1.Text = returndata;
        stream.Close();//关闭网络流
        client.Close();//关闭客户端




    }





}

}

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
    • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
    • ¥20 有关区间dp的问题求解
    • ¥15 多电路系统共用电源的串扰问题
    • ¥15 slam rangenet++配置
    • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
    • ¥15 ubuntu子系统密码忘记
    • ¥15 保护模式-系统加载-段寄存器
    • ¥15 电脑桌面设定一个区域禁止鼠标操作
    • ¥15 求NPF226060磁芯的详细资料