C# Socket 模拟http服务器帮助类

0x01 写在前面

0x02 Http协议

0x03 TCP/IP

0x04 看代码

0x05 总结

0x01 写在前面

  由于工作中,经常需要在服务器之间,或者进程之间进行通信,分配任务等。用Socket操作,太麻烦了,需要建立连接,处理消息。所以

准备创建一个Socket模拟Http服务器的帮助类,来直接通过WebClient进行调用。

0x02 Http协议

我的理解:http协议,其实就是依托于tcp/ip的一个协议,也是可以通过socket发送消息,只是说。发送的内容格式满足http的条件,就可以被理解成http协议。

常用Http头。 Http版本也是可以写成1.1的。

HTTP/1.0 200 OK
Content-Type: text/html
Connection: keep-alive
Content-Encoding: utf-8

0x03 TCP/IP

我的理解:TCP/IP协议其实是某一类协议的大分类了,很多协议都是基于这个协议来传递消息的。更详细的信息,自己搜索一下。

0x04 看代码

SocketHttpHelper.cs  socket模拟http帮助类

  1 public class SocketHttpHelper
  2 {
  3     private string ip = "127.0.0.1";
  4     private int port = 8123;
  5     private int count = 0;
  6     private Socket server = null;
  7 
  8     public string DefaultReturn = string.Empty;
  9 
 10     public event Func<string, string, string> Handler = null;
 11 
 12     public SocketHttpHelper()
 13     {
 14     }
 15 
 16     public SocketHttpHelper(string ip, int port)
 17     {
 18         this.ip = ip;
 19         this.port = port;
 20     }
 21 
 22     public void StartListen(int count = 10)
 23     {
 24         this.count = count;
 25         Thread t = new Thread(new ThreadStart(ProcessThread));
 26         t.IsBackground = true;
 27         t.Start();
 28     }
 29 
 30     public void CloseSocket()
 31     {
 32         try
 33         {
 34             server.Close();
 35         }
 36         catch { }
 37     }
 38 
 39     private void ProcessThread()
 40     {
 41         server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
 42         server.Bind(new System.Net.IPEndPoint(System.Net.IPAddress.Parse(ip), port));
 43         server.Listen(count);
 44         while (true)
 45         {
 46             try
 47             {
 48                 Socket client = server.Accept();
 49                 ThreadPool.QueueUserWorkItem(new WaitCallback(ListenExecute), client);
 50             }
 51             catch { }
 52             finally
 53             {
 54             }
 55         }
 56     }
 57 
 58     private void ListenExecute(object obj)
 59     {
 60         Socket client = obj as Socket;
 61         try
 62         {
 63             string ip = (client.RemoteEndPoint as System.Net.IPEndPoint).Address.ToString();
 64             byte[] buffer = new byte[1024];
 65             int count = client.Receive(buffer);
 66             if (count > 0)
 67             {
 68                 string content = Encoding.UTF8.GetString(buffer, 0, count);
 69 
 70                 // 解析 content
 71                 Regex actionRegex = new Regex(@"GET\s+/(?<action>\w+)\?(?<args>[^\s]{0,})");
 72                 string action = actionRegex.Match(content).Groups["action"].Value;
 73                 string args = actionRegex.Match(content).Groups["args"].Value;
 74                 string headStr = @"HTTP/1.0 200 OK
 75 Content-Type: text/html
 76 Connection: keep-alive
 77 Content-Encoding: utf-8
 78 
 79 ";
 80                 if (Handler != null)
 81                 {
 82                     try
 83                     {
 84                         string result = Handler(action, args);
 85                         string data = string.Format(headStr + result);
 86                         client.Send(Encoding.UTF8.GetBytes(data));
 87                     }
 88                     catch { }
 89                     finally
 90                     {
 91                     }
 92                 }
 93                 else
 94                 {
 95                     string data = string.Format(headStr + DefaultReturn);
 96                     client.Send(Encoding.UTF8.GetBytes(data));
 97                 }
 98             }
 99         }
100         catch { }
101         finally
102         {
103             try
104             {
105                 client.Shutdown(SocketShutdown.Both);
106                 client.Close();
107                 client.Dispose();
108             }
109             catch { }
110         }
111     }
112 }
View Code

0x05 总结

由于,每次都要从Socket开始写,写多了才发现,原来需要写一个公用类,点都不费时间。

转载于:https://www.cnblogs.com/Supperlitt/p/5517947.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
namespace ServerDemo { partial class ServerDemo { /// /// 必需的设计器变量。 /// private System.ComponentModel.IContainer components = null; /// /// 清理所有正在使用的资源。 /// /// 如果应释放托管资源,为 true;否则为 false。 protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows 窗体设计器生成的代码 /// /// 设计器支持所需的方法 - 不要 /// 使用代码编辑器修改此方法的内容。 /// private void InitializeComponent() { this.lb_ServerInfo = new System.Windows.Forms.ListBox(); this.bn_Resume = new System.Windows.Forms.Button(); this.bn_Stop = new System.Windows.Forms.Button(); this.bn_Start = new System.Windows.Forms.Button(); this.listBox1 = new System.Windows.Forms.ListBox(); this.cmbClient = new System.Windows.Forms.ComboBox(); this.btnSendto = new System.Windows.Forms.Button(); this.labClientCount = new System.Windows.Forms.Label(); this.SuspendLayout(); // // lb_ServerInfo // this.lb_ServerInfo.FormattingEnabled = true; this.lb_ServerInfo.ItemHeight = 12; this.lb_ServerInfo.Location = new System.Drawing.Point(14, 32); this.lb_ServerInfo.Name = "lb_ServerInfo"; this.lb_ServerInfo.Size = new System.Drawing.Size(572, 100); this.lb_ServerInfo.TabIndex = 61; // // bn_Resume // this.bn_Resume.Location = new System.Drawing.Point(174, 3); this.bn_Resume.Name = "bn_Resume"; this.bn_Resume.Size = new System.Drawing.Size(97, 23); this.bn_Resume.Ta
以下是一个简单的C# Socket服务器封装的示例: ```csharp using System; using System.Collections.Generic; using System.Net; using System.Net.Sockets; using System.Text; public class SocketServer { private readonly List<Socket> _clients = new List<Socket>(); private readonly Socket _listener; public SocketServer(int port) { _listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); _listener.Bind(new IPEndPoint(IPAddress.Any, port)); _listener.Listen(10); _listener.BeginAccept(AcceptCallback, null); Console.WriteLine($"Server started on port {port}"); } private void AcceptCallback(IAsyncResult ar) { var client = _listener.EndAccept(ar); _clients.Add(client); Console.WriteLine($"Client connected: {client.RemoteEndPoint}"); var buffer = new byte[1024]; client.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, ReceiveCallback, client); _listener.BeginAccept(AcceptCallback, null); } private void ReceiveCallback(IAsyncResult ar) { var client = (Socket)ar.AsyncState; var bytesRead = client.EndReceive(ar); if (bytesRead > 0) { var message = Encoding.ASCII.GetString(buffer, 0, bytesRead); Console.WriteLine($"Received message from {client.RemoteEndPoint}: {message}"); // Echo the message back to the client var responseBuffer = Encoding.ASCII.GetBytes(message); client.BeginSend(responseBuffer, 0, responseBuffer.Length, SocketFlags.None, null, null); // Continue listening for messages client.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, ReceiveCallback, client); } else { Console.WriteLine($"Client disconnected: {client.RemoteEndPoint}"); _clients.Remove(client); } } public void Close() { _listener.Close(); foreach (var client in _clients) { client.Shutdown(SocketShutdown.Both); client.Close(); } } } ``` 使用示例: ```csharp var server = new SocketServer(1234); Console.ReadLine(); server.Close(); ``` 这个封装实现了一个简单的Socket服务器,它监听指定的端口,并在有连接时接受客户端连接。每当有数据从客户端传入时,服务器会将其回显到客户端。可以通过调用Close()方法来关闭服务器

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值