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 import arcpy出现importing _arcgisscripting 找不到相关程序
    • ¥15 onvif+openssl,vs2022编译openssl64
    • ¥15 iOS 自定义输入法-第三方输入法
    • ¥15 很想要一个很好的答案或提示
    • ¥15 扫描项目中发现AndroidOS.Agent、Android/SmsThief.LI!tr
    • ¥15 怀疑手机被监控,请问怎么解决和防止
    • ¥15 Qt下使用tcp获取数据的详细操作
    • ¥15 idea右下角设置编码是灰色的
    • ¥15 全志H618ROM新增分区
    • ¥15 在grasshopper里DrawViewportWires更改预览后,禁用电池仍然显示