using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Newtonsoft.Json;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Reflection;
using System.Net.Sockets;
using System.Web;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
public void Start()
{
if (isRunning)
return;
int len = 0;//端口
byte[] buf = new byte[1024];
//创建服务端Socket
Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
serverSocket.Bind(new IPEndPoint(IPAddress.Parse(ServerIP), ServerPort));
serverSocket.Listen(10);
isRunning = true;
//输出服务器状态
Console.WriteLine("Sever is running at http://{0}:{1}/.", ServerIP, ServerPort);
//连接客户端
Socket clent = serverSocket.Accept();
len = clent.Receive(buf);
Console.WriteLine("收到 [{0}] 数据", len);
Console.WriteLine(Encoding.ASCII.GetString(buf));
string ss = "HTTP/1.0 200 OK\nContent-Type:text/html\n\n Welcome!<br>Now Time:{0}";
string ss1 = "nihao";
DateTime dt = DateTime.Now;
string nn = string.Format(ss, dt.ToString());
len = clent.Send(Encoding.ASCII.GetBytes(nn));
clent.Send(Encoding.ASCII.GetBytes(ss1));
Console.WriteLine("发送 [{0}] 数据", len);
Console.WriteLine(ss);
clent.Close();
}
HTTP/1.0 200 OK\nContent-Type:text/html\n\n
HTTP/1.0是协议版本
200是http statusCode(状态码)成功
nContent-Type 是header关键字-数据类型
使用post-man工具测试
使用post方式发送数据
得到服务器的返回结果
如下图标号3的结果