连接时一切都很顺利,除非我关闭连接并重新打开(一切都很好,直到现在,数据收到很好)。
当我尝试在流中写入时弹出错误:
无法访问已处置的对象:'System.Net.Sockets.NetworkStream'!!
我每次连接时都尝试使用新的客户端实例
关闭连接时:我已尝试过所有这些内容,例如_client.GetStream().Close();
_client.Close();
但一切都失败了
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
myform = this;
}
public static Form1 myform;
Client c1;
public void ConnectButton_Click(object sender, EventArgs e)
{
c1 = new Client();
try
{ c1.Connect(IPADRESStext.Text, PORTNUMBERtext.Text); }
catch (Exception ex)
{ MessageBox.Show(ex.ToString()); }
}
private void CloseButton_Click(object sender, EventArgs e)
{
c1.Disconnect();
}
}
public sealed partial class Client
{
public void SendData(byte[] data)
{ _sender.SendData(data); }
public event EventHandler<DataReceivedEventArgs> DataReceived;
public void Connect(string IPADRESStxt, string PORTNUMBERtxt)
{
sq = new sequence();
_client = new TcpClient(IPADRESStxt, Int32.Parse(PORTNUMBERtxt));
_stream = _client.GetStream();
_sender = new Sender(_stream);
_receiver = new Receiver(_stream);
_receiver.DataReceived += OnDataReceived;
}
public void Disconnect()
{
_stream.Close();
_client.Close();
//_client.Client.Disconnect(false);
//tcpClient.GetStream().Close();
//tcpClient.Close();
}
private void OnDataReceived(object sender, DataReceivedEventArgs e)
{
var handler = DataReceived;
if (handler != null) DataReceived(this, e); // re-raise event
}
private TcpClient _client;
private NetworkStream _stream;
private Receiver _receiver;
private Sender _sender;
}
public sealed partial class Client
{
private sealed class Sender
{
internal void SendData(byte[] data)
{
_stream.Write(data, 0, data.Length); /// 2 When trying to execute this instruction
}
internal Sender(NetworkStream stream)
{
_stream = stream;
_thread = new Thread(Run);
_thread.Start();
}
private void Run()
{
// Code Code Code
SendData(Sframe); /// 1 Error pops up here
}
private NetworkStream _stream;
private Thread _thread;
}
}