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 _9.socket服务器端
{
public partial class Form1 : Form
{
private List<Socket> proxSocket=new List<Socket>();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
textBox1.Text = "192.168.0.100";
textBox2.Text = "8080";
//1.创建socket对象--1.设置网络寻址协议,2.数据传输方式,3.设置通信协议
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
this.textBox3.Text = "创建服务器端socket对象\r\n" + textBox3.Text;
//2.绑定端口
socket.Bind(new IPEndPoint(IPAddress.Parse(textBox1.Text), int.Parse(textBox2.Text)));
//3.开启监听
socket.Listen(10);
//4.开始接收客户端连接
this.textBox3.Text = "开始接收客户端连接\r\n" + textBox3.Text;
ThreadPool.QueueUserWorkItem(new WaitCallback(SartSocket), socket);
}
private void SartSocket(object state)
{
while (true) {
Socket prSocket = ((Socket)state).Accept();//在接受链接时候堵塞线程,直到有客户端链接
this.textBox3.Invoke(new Action(() => {
this.textBox3.Text = string.Format(@"一个客户端:{0}连接上\r\n{1}", prSocket.RemoteEndPoint.ToString(), textBox3.Text);
}));
proxSocket.Add(prSocket);
#region 初次代码
//byte[] bytes = Encoding.Default.GetBytes("我是你大爷");
//proxSocket.Send(bytes, 0, bytes.Length, SocketFlags.None);
发送空字节消息,走了
//proxSocket.Shutdown(SocketShutdown.Both);
//this.textBox3.Invoke(new Action(() => {
// this.textBox3.Text = "关闭\r\n" + textBox3.Text;
//}));
//proxSocket.Close();
socket.Shutdown(SocketShutdown.Both);
((Socket)state).Close();
#endregion
ThreadPool.QueueUserWorkItem(new WaitCallback(ReceiveDate), prSocket);
}
}
private void ReceiveDate(object state)
{
//接受客户端来的消息
byte[] data = new byte[1024 * 1024];
while (true)
{
//方法的返回值表示实际上接收的数据长度(字节数)
try {
int realLen = ((Socket)state).Receive(data, 0, data.Length, SocketFlags.None);
//表示对方退出了
if (realLen == 0)
{
this.textBox3.Invoke(new Action(() => {
textBox3.Text = $"客户端{ ((Socket)state).RemoteEndPoint.ToString()}退出了\r\n{ textBox3.Text}";
}));
((Socket)state).Shutdown(SocketShutdown.Both);
((Socket)state).Close();
proxSocket.Remove(((Socket)state));
return;
}
string x = Encoding.Default.GetString(data, 0, realLen);
this.textBox3.Invoke(new Action(() => {
textBox3.Text = $"接收客户端发送来的消息{ ((Socket)state).RemoteEndPoint.ToString()}{x}\r\n{ textBox3.Text}";
}));
}
catch{
}
}
}
private void button2_Click(object sender, EventArgs e)
{
if (proxSocket!=null) {
foreach (var item in proxSocket)
{
if (item.Connected) {
byte[] bytes = Encoding.Default.GetBytes(textBox4.Text + item.GetHashCode().ToString());
item.Send(bytes, 0, bytes.Length, SocketFlags.None);
}
}
}
}
}
}
Socket服务器端笔记
最新推荐文章于 2023-11-02 10:48:37 发布