概述
上位机–客户端程序撰写部分2022/10/01
验证可行性:通过NetAssist网络通信助手(发送与接收数据????),本地环回地址
客户端代码中加入了关闭连接的按键(在通信中位主动方)
#region TCP/IP 客户端
//创建Client套接字
Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Thread ReceiveMsgThread;
/// <summary>
/// 连接服务器
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Bt_Start_Click(object sender, EventArgs e)
{
//连接服务器需要传递服务器的ip地址与端口号
IPEndPoint point = new IPEndPoint(IPAddress.Parse(Cb_local_Ip.Text), int.Parse(Cb_local_Port.Text));
//连接服务器
//使用try catch 的原因:会遇到服务器端口号ip地址被占用的情况
try
{
client.Connect(point);
}
catch (Exception ex)
{
MessageBox.Show("与服务器连接失败" + ex);
}
MessageBox.Show("与服务器连接成功");
ReceiveMsgThread = new Thread(ReceiveMsg);
ReceiveMsgThread.Start();
//Task.Run(new Action(() =>
//{
// ReceiveMsg();
//}));
Bt_Start.Enabled = false;
}
/// <summary>
/// 接收消息(客户端接收服务器消息)
/// </summary>
/// <param name="client"></param>
private void ReceiveMsg()
{
while (true)
{
byte[] b = new byte[1024 * 1024 * 2];
int length = 0;
try
{
length = client.Receive(b);
}
catch
{
MessageBox.Show("服务器断开连接");
}
if (length > 0)
{
string msg = Encoding.Default.GetString(b, 0, length);
//将状态更新在信息栏中
this.BeginInvoke(new EventHandler(delegate
{
Tb_Msg_Show.AppendText(client + ":" + msg +"rn");
}));
}
}
}
/// <summary>
/// 发送消息
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Bt_SendMsg_Click(object sender, EventArgs e)
{
if (client != null)
{
try
{
this.BeginInvoke(new EventHandler(delegate
{
Tb_Msg_Show.AppendText("客户端" + Tb_SendMsg.Text.Trim() + "rn");//
}));
client.Send(Encoding.Default.GetBytes(Tb_SendMsg.Text.Trim()));
}
catch (Exception ex)
{
Tb_Msg_Show.AppendText("出现错误" + ex.Message);
}
}
}
private void Bt_Close_Click(object sender, EventArgs e)
{
try
{
//关闭线程
ReceiveMsgThread.Abort();
//关闭socket类实例
client.Close();
MessageBox.Show("客户端断开连接");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
#endregion
上位机–服务端程序撰写部分2022/10/02
验证可行性:通过NetAssist网络通信助手(发送与接收数据????)
通信中为被动方,所以没有加入关闭连接按钮
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Threading;
namespace Socket_part
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
#region TCP/IP 服务端
//创建Socket套接字
Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//创建键值集合 存放待处理客户端连接序列
private Dictionary<string, Socket> Clientlist = new Dictionary<string, Socket>();
/// <summary>
/// 启动网络服务
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Bt_Start_Click(object sender, EventArgs e)
{
//if (!server.IsBound)
//{
//连接服务器需要传递服务器的ip地址与端口号
IPEndPoint point = new IPEndPoint(IPAddress.Parse(Cb_local_Ip.Text), int.Parse(Cb_local_Port.Text));
//连接服务器
//使用try catch 的原因:会遇到服务器端口号ip地址被占用的情况
try
{
server.Bind(point);
}
catch (Exception ex)
{
MessageBox.Show("无法启动服务器" + ex);
}
//建立监听序列
//3-挂起序列的最大长度(不使用accept时)
//不使用accept 相当于所有请求放在碗里 3就是碗的容量 超过了就放不下了
//使用accept 相当于连接放在另一个地方 accept 从另一个地方往碗里拿 一次只拿一个
server.Listen(3);
Task.Run(new Action(() =>
{
ListenSocket();
}));
MessageBox.Show("服务器启动成功");
}
/// <summary>
/// 创建监听程序
/// </summary>
private void ListenSocket()
{
while (true)
{
Client = server.Accept();//抓取客户端发来的连接请求
string client = Client.RemoteEndPoint.ToString(); //获取客户端的IP地址与端口号,知道谁连进来
// MessageBox.Show(client + ":连接了服务器");
Clientlist.Add(client, Client);//字典键值对
//已连接的客户端
OnlineClient(client, true);
Task.Run(new Action(() =>
{
ReceiveMsg(Client);
}));
}
}
/// <summary>
/// 接收消息(服务器接收客户端消息)
/// </summary>
/// <param name="client"></param>
private void ReceiveMsg(Socket Client)
{
while (true)
{
byte[] b = new byte[1024 * 1024 * 2];
int length = 0;
string client = Client.RemoteEndPoint.ToString();
try
{
length = Client.Receive(b);
}
catch
{
OnlineClient(client, false);
MessageBox.Show(client + "失去连接" + "rn");
Clientlist.Remove(client);
break;
}
if (length > 0)
{
string msg = Encoding.Default.GetString(b, 0, length);
//将状态更新在信息栏中
this.BeginInvoke(new EventHandler(delegate
{
Tb_Msg_Show.AppendText(client + ":" + msg + "rn");
}));
}
else
{
MessageBox.Show(client + "失去连接" + "rn");
Clientlist.Remove(client);
}
}
}
/// <summary>
/// 发送消息
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Bt_SendMsg_Click(object sender, EventArgs e)
{
if (Cb_OnLineClient.Items.Count != 0)
{
this.BeginInvoke(new EventHandler(delegate
{
Tb_Msg_Show.AppendText("服务器" + Tb_SendMsg.Text.Trim() + "rn");
}));
string client = Cb_OnLineClient.SelectedItem.ToString();//选择要发送的客户端
Clientlist[client].Send(Encoding.Default.GetBytes(Tb_SendMsg.Text));
}
else
{
MessageBox.Show("请选择客户端");
}
}
/// <summary>
/// 群发消息
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Bt_SendMsg_Click2(object sender, EventArgs e)
{
if (Cb_OnLineClient.Items.Count > 0)
{
this.BeginInvoke(new EventHandler(delegate
{
Tb_Msg_Show.AppendText("服务器" + Tb_SendMsg.Text.Trim() + "rn");
}));
//
foreach (string item in Cb_OnLineClient.Items)
{
Clientlist[item].Send(Encoding.Default.GetBytes(Tb_SendMsg.Text));
}
}
else
{
MessageBox.Show("请选择客户端");
}
}
/// <summary>
/// 已连接客户端列表更新
/// </summary>
/// <param name="client"></param>
/// <param name="p"></param>
private void OnlineClient(string client, bool p)
{
if (Cb_OnLineClient.InvokeRequired)//需要跨线程操作
{
Invoke(new Action(() =>
{
if (p)
{
Cb_OnLineClient.Items.Add(client);
}
else
{
foreach (string item in Cb_OnLineClient.Items)
{
if (item == client)
{
Cb_OnLineClient.Items.Add(client);
break;
}
}
}
}));
}
else
{
if (p)
{
Cb_OnLineClient.Items.Add(client);
}
else
{
foreach (string item in Cb_OnLineClient.Items)
{
if (item == client)
{
Cb_OnLineClient.Items.Add(client);
break;
}
}
}
}
}
#endregion
}
}
最后
以上就是知性枕头为你收集整理的C# TCP/IP通信(存小问题/大体欧克)的全部内容,希望文章能够帮你解决C# TCP/IP通信(存小问题/大体欧克)所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复