Socket伺服器端筆記
阿新 • • 發佈:2021-01-03
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);
}
}
}
}
}
}