///服务器端:
/// <summary>
/// 1, 建立IPAdress(.Any或者.phase方法) 与IPEndPoint(new IPEndPoint),
/// 建立Socket, 命名为SocketWatch, 绑定其. 设定监听数量
/// 2, 建立新线程, 执行 监听(Listen)函数.
/// 其中Listen中有Accept方法(阻塞线程), 需要一直执行, 使用While.
/// Accept方法 返回一个Socket, 命名为SocketSend.
/// 3,建立Receive函数, 并建立新线程执行 Receive函数.
/// Receive函数接收参数SocketSend, 并使用SocketSend.
/// Receive一直接收数据, 使用While , 并返回一个整型r, r==0时候while停止.
/// 使用Encoding.UTF8.GetString 将字节转化为字符串, 显示.
/// 使用字典存入连入的IP和Socket, 并用下拉框选择Socket与其通信
/// </summary>
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Socket_winform2021_11_20
{
public partial class Server_Form1 : Form
{
public Server_Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//创建一个负责监听的socket P183
Socket socketWatch = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
//IPAddress ip = IPAddress.Any; //IPAddress.Parse(textBox1.Text);
IPAddress ip = IPAddress.Parse(textBox1.Text); //
IPEndPoint point = new IPEndPoint(ip,Convert.ToInt32(textPort.Text));
//让负责监听的socket绑定IP地址和端口号
socketWatch.Bind(point);
ShowMsg("监听成功");
//设置监听队列;设置某一时刻,连入服务端的最大客户端数量
socketWatch.Listen(10);
Thread th = new Thread(Listen);
th.IsBackground = true;
th.Start(socketWatch);
}
Socket socketSend;
//将远程客户端的IP地址和Socket存入字典
Dictionary<string, Socket> dicSocket =
new Dictionary<string, Socket>(); //IP地址读出来是个字符串, 值的类型是socket
/// <summary>
/// 等待客户端的连接, 并且创建与之通信的socketS
/// </summary>
void Listen(object o) //用新线程执行,传参数必须是object类型
{
Socket socketWatch = o as Socket; //成功则返回对象, 失败范围null
//负责监听的Socket 来接受客户端的连接 创建跟客户端通信的socket
while (true)
{
try
{
socketSend = socketWatch.Accept(); //会阻碍主线程的执行,等待新的连接
//将远程客户端的IP地址和Socket存入字典
dicSocket.Add(socketSend.RemoteEndPoint.ToString(), socketSend);
//将远程客户端的IP地址和Socket存入下拉框
cboUsers.Items.Add(socketSend.RemoteEndPoint.ToString());
ShowMsg(socketSend.RemoteEndPoint.ToString() + "连接成功");
//开启一个新线程,不停的接收客户端发来的消息
Thread th = new Thread(Recive_);
th.IsBackground = true;
th.Start(socketSend);
}
catch
{}
//byte[] buffer = new byte[1024 * 1024 * 2];
实际接收的有效字节数
//int r = socketSend.Receive(buffer); //只接收了一次
//string str = Encoding.UTF8.GetString(buffer, 0, r);//index 起始数据的索引,r 接收数据的字节数
//ShowMsg(socketSend.RemoteEndPoint+":"+str);
}
}
/// <summary>
/// 服务器不停的接收客户端发送来的消息
/// </summary>
/// <param name="o"></param>
void Recive_(object o)
{
Socket socketSend = o as Socket;
while (true)
{
try
{
byte[] buffer = new byte[1024 * 1024 * 2];
//实际接收的有效字节数
int r = socketSend.Receive(buffer); //只接收了一次 没有消息时,r为0
if (r==0)
{
break;
}
//index 起始数据的索引,r 接收数据的字节数
string str = Encoding.UTF8.GetString(buffer, 0, r);
ShowMsg(socketSend.RemoteEndPoint + ":" + str);
}
catch
{}
}
}
void ShowMsg(string str)
{
textLog.AppendText(str + "\r\n");
}
private void Form1_Load(object sender, EventArgs e)
{
Control.CheckForIllegalCrossThreadCalls = false;
}
private void btnSend_Click(object sender, EventArgs e)
{
string str = TxTMsg.Text;
byte[] buffer = Encoding.UTF8.GetBytes(str);//将字符串转换为字节
string ip = cboUsers.SelectedItem.ToString();
dicSocket[ip].Send(buffer);
//socketSend.Send(buffer);
}
}
}
///客户端:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Socket_Client
{
public partial class Client : Form
{
public Client()//P185 3分30
{
InitializeComponent();
}
Socket socketSend;
private void button1_Click(object sender, EventArgs e)
{
}
private void btn_Start_Click(object sender, EventArgs e)
{
//创建负责通信的socket
socketSend = new Socket(
AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress iP = IPAddress.Parse(Text_IP.Text);
IPEndPoint endPoint = new IPEndPoint(iP, Convert.ToInt32(Text_Port.Text));
//客户端连接服务器端
socketSend.Connect(endPoint); //服务器端是绑定,
ShowMsg("连接成功!");
Thread th = new Thread(Recieve);
th.IsBackground = true;
th.Start(socketSend);
}
/// <summary>
/// 不停的接收服务端发来的消息
/// </summary>
/// <param name="o"></param>
void Recieve(object o)
{
Socket socketSendC = o as Socket;
while (true)
{
try
{
byte[] buffer = new byte[1024 * 1024 * 2];
int r = socketSendC.Receive(buffer);
if (r == 0)
{
break;
}
string str = Encoding.UTF8.GetString(buffer, 0, r);//将字节转化为字符串
ShowMsg(socketSendC.RemoteEndPoint + ":" + str);//地址+字符串
}
catch
{ }
}
}
void ShowMsg(string s)
{
TextLog.AppendText(s+"\r\n");
}
/// <summary>
/// 客户端给服务器发送消息
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnSend_Click(object sender, EventArgs e)
{
string str = TextMsg.Text.Trim();//移除前面和后面的空白字符
byte[] buffer = Encoding.UTF8.GetBytes(str);
socketSend.Send(buffer);
}
private void Client_Load(object sender, EventArgs e)
{
Control.CheckForIllegalCrossThreadCalls = false;
}
}
}
C# socket 建立多线程服务器端和客户端
最新推荐文章于 2024-06-26 11:14:11 发布