我需要从我的虚拟 com 端口读取数据并检测消息“Dreq”。一旦我按下连接按钮,它就会连接到我的 COM8 端口并开始读取新线程。我还有一个断开连接按钮,我希望在其中关闭读数并断开与 COM8 端口的连接。但是,我在关闭 BeginRead 时遇到问题。
public partial class Form1 : Form
{
SerialPort sp;
Stream stream;
IAsyncResult recv_result;
private void button1_Click(object sender, EventArgs e)
{
sp = new SerialPort("COM8", 9600);
sp.Open();
sp.ReadTimeout = 50000;
sp.NewLine = "\n\r\0";
stream = sp.BaseStream;
recv_result = stream.BeginRead(new byte[1], 0, 0, new
AsyncCallback(ReadCallBack), stream);
}
private void ReadCallBack(IAsyncResult ar)
{
Stream stream = (Stream)ar.AsyncState;
string temp;
while (stream.CanRead)
{
temp = sp.ReadLine();
// ... do something with temp
}
}
private …Run Code Online (Sandbox Code Playgroud) 经过长时间的休息,我试图刷新我对System.Net.Sockets的记忆,但我遇到了连接甚至2台机器的问题.
例外:不允许发送或接收数据的请求,因为套接字未连接(当使用sendto调用在数据报套接字上发送时)没有提供地址
服务器代码:
private void startButton_Click(object sender, EventArgs e)
{
LocalEndpoint = new IPEndPoint(IPAddress.Parse("192.168.1.103"), 4444);
_Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_Socket.Bind(LocalEndpoint);
_Socket.Listen(10);
_Socket.BeginAccept(new AsyncCallback(Accept), _Socket);
}
private void Accept(IAsyncResult _IAsyncResult)
{
Socket AsyncSocket = (Socket)_IAsyncResult.AsyncState;
AsyncSocket.EndAccept(_IAsyncResult);
buffer = new byte[1024];
AsyncSocket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(Receive), AsyncSocket);
}
private void Receive(IAsyncResult _IAsyncResult)
{
Socket AsyncSocket = (Socket)_IAsyncResult.AsyncState;
AsyncSocket.EndReceive(_IAsyncResult);
strReceive = Encoding.ASCII.GetString(buffer);
Update_Textbox(strReceive);
buffer = new byte[1024];
AsyncSocket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(Receive), AsyncSocket);
}
Run Code Online (Sandbox Code Playgroud)
客户代码:
private void connectButton_Click(object sender, …Run Code Online (Sandbox Code Playgroud)