需要定义
/// <summary>
/// 负责通信的socket
/// </summary>
Socket socketSend;
/// <summary>
/// 负责监听Socket
/// </summary>
Socket socket;
/// <summary>
/// 存放连接的socket
/// </summary>
Dictionary<string, Socket> dictionary = new Dictionary<string, Socket>();
监听IP、端口文章来源:https://www.toymoban.com/news/detail-621122.html
//取消跨线程检查
Control.CheckForIllegalCrossThreadCalls = false;
//将窗口最大化
this.WindowState = FormWindowState.Maximized;
//创建监听的socket,
//SocketType.Stream 流式对应tcp协议
//Dgram,数据报对应UDP协议
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//创建IP地址和端口号
IPAddress ip = IPAddress.Parse("192.166.2.48");//IPAddress.Parse(textServerIP.Text);
int port = Convert.ToInt32(5555);
IPEndPoint iPEndPoint = new IPEndPoint(ip, port);
//让负责监听的Socket绑定ip和端口号
socket.Bind(iPEndPoint);
using (StreamWriter sw = new StreamWriter(filePath, true)) { sw.WriteLine("监听成功!" + ip + ";" + port + ":\t" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); }
//设置监听队列
socket.Listen(10);//一段时间内可以连接到的服务器的最大数量
Thread thread = new Thread(Listen);
thread.IsBackground = true;
thread.Start(socket);
/// <summary>
/// 使用线程来接收数据
/// </summary>
/// <param name="o"></param>
private void Listen(object o)
{
Socket socket = o as Socket;
while (true)
{
//负责监听的socket是用来接收客户端连接
//创建负责通信的socket
socketSend = socket.Accept();
dictionary.Add(socketSend.RemoteEndPoint.ToString(), socketSend);
// clientCombo.Items.Add(socketSend.RemoteEndPoint.ToString());
//开启新线程,接收客户端发来的信息
Thread th = new Thread(receive);
th.IsBackground = true;
th.Start(socketSend);
}
}
//服务器接收客户端传来的消息
private void receive(object o)
{
Socket socketSend = o as Socket;
while (true)
{
try
{
//客户端连接成功后,服务器接收客户端发来的消息
byte[] buffer = new byte[1024 * 1024 * 2];//2M大小
//接收到的有效字节数
int length = socketSend.Receive(buffer);
if (length == 0)
{
using (StreamWriter sw = new StreamWriter(filePath, true)) { sw.WriteLine("TCP连接下线了:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); }
dictionary[socketSend.RemoteEndPoint.ToString()].Shutdown(SocketShutdown.Both);
dictionary[socketSend.RemoteEndPoint.ToString()].Disconnect(false);
dictionary[socketSend.RemoteEndPoint.ToString()].Close();
break;
}
string str = Encoding.ASCII.GetString(buffer, 0, length);
//接收过来的消息
if (str.Length > 0)
{
TCPStr = str;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
发送消息文章来源地址https://www.toymoban.com/news/detail-621122.html
Socket socket; //连接
private void connectBtn_Click(object sender, EventArgs e)
{
try
{
//创建负责通信的socket
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//地址、端口
IPAddress ip = IPAddress.Parse("192.166.2.48");
int serverPort = Convert.ToInt32(5555);
IPEndPoint port = new IPEndPoint(ip, serverPort);
//连接到服务器
socket.Connect(port);
//启动接收数据线程
Thread th = new Thread(receive);
th.IsBackground = true;
th.Start();
}
catch { }
}
/// <summary>
/// 发消息
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void sendMsgBtn_Click(object sender, EventArgs e)
{
try
{
string txt = textBox1.Text;
byte[] buffer = Encoding.ASCII.GetBytes(txt);//ascii编码
socket.Send(buffer);
}
catch { }
}
到了这里,关于C# WinForm实现TCP收发信息的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!