问题描述
- 用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('')); //listBox1.Text = returndata; stream.Close();//关闭网络流 client.Close();//关闭客户端 } }
}
时间: 2024-10-26 00:40:42