旧连接代码:
//创建用于通讯的socket
PlcClass.Instance.socketsend = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress ip = IPAddress.Parse(BaseData.Instance.tcp_ip);
IPEndPoint port = new IPEndPoint(ip, Convert.ToInt32(BaseData.Instance.tcp_port));
//连接对应的端口
PlcClass.Instance.socketsend.Connect(port);
// 接收信息
byte[] buffer = new byte[1024 * 1024 * 2];
int i = socketsend.Receive(buffer);
string str = Encoding.UTF8.GetString(buffer, 0, i);
新异步连接代码
TcpClient tcpClient;
byte[] ReadBytes = new byte[1024 * 1024];
//连接服务器
public void ConnectServer(string ip, int port)//填写服务端IP与端口
{
try
{
tcpClient = new System.Net.Sockets.TcpClient();//构造Socket
tcpClient.BeginConnect(IPAddress.Parse(ip), port, Lianjie, null);//开始异步
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
//连接判断
void Lianjie(IAsyncResult ar)
{
try
{
if (!tcpClient.Connected)
{
IPAddress ip = IPAddress.Parse(BaseData.Instance.tcp_ip);
tcpClient.BeginConnect(ip, Convert.ToInt32(BaseData.Instance.tcp_port), Lianjie, null);
}
else
{
tcpClient.EndConnect(ar);//结束异步连接
tcpClient.GetStream().BeginRead(ReadBytes, 0, ReadBytes.Length, ReceiveCallBack, null);
}
}
catch (Exception ex)
{
MessageBox.Show("连接失败:" + ex.Message);
}
}
//接收消息
void ReceiveCallBack(IAsyncResult ar)
{
try
{
int len = tcpClient.GetStream().EndRead(ar);//结束异步读取
if (len > 0)
{
string str = Encoding.UTF8.GetString(ReadBytes, 0, len);
str = Uri.UnescapeDataString(str);
,...逻辑处理....
tcpClient.GetStream().BeginRead(ReadBytes, 0, ReadBytes.Length, ReceiveCallBack, null);
}
else
{
tcpClient = null;
ConnectServer(BaseData.Instance.tcp_ip, Convert.ToInt32(BaseData.Instance.tcp_port));
}
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
//发送消息
public void SendMsg(string msg)
{
try
{
byte[] msgBytes = Encoding.UTF8.GetBytes(msg);
tcpClient.GetStream().BeginWrite(msgBytes, 0, msgBytes.Length, (ar) => {
tcpClient.GetStream().EndWrite(ar);//结束异步发送
}, null);//开始异步发送
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
/// <summary>
/// 断开连接
/// </summary>
public void TcpClose()
{
try
{
if (tcpClient != null && tcpClient.Client.Connected)
tcpClient.Close();
if (!tcpClient.Client.Connected)
{
tcpClient.Close();//断开挂起的异步连接
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}