编辑
2023-05-17
软件编程
0

目的 仅使用TCP服务程序实现网页实时显示与控件交互。

新建控制台程序

image.png

复制下面代码

c#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; using System.Threading.Tasks; namespace http_TCP { internal class Program { static void Main(string[] args) { Server server = new Server(); } } class Server { private TcpListener tcpListener; private Thread listenThread; public Server() { this.tcpListener = new TcpListener(IPAddress.Any, 3000); this.listenThread = new Thread(new ThreadStart(ListenForClients)); this.listenThread.Start(); Console.WriteLine("Server started at "+ IPAddress.Any+" :"+ 3000+" @ " + DateTime.Now.ToString()); } private void ListenForClients() { this.tcpListener.Start(); while (true) { //blocks until a client has connected to the server TcpClient client = this.tcpListener.AcceptTcpClient(); //create a thread to handle communication //with connected client Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm)); clientThread.Start(client); } } private void HandleClientComm(object client) { TcpClient tcpClient = (TcpClient)client; Console.WriteLine("Client @[{0}] connected @{1}", tcpClient.Client.LocalEndPoint, DateTime.Now.ToString()); NetworkStream clientStream = tcpClient.GetStream(); byte[] message = new byte[4096]; int bytesRead = 0; //bool isRight=false; while (true) { bytesRead = 0; try { //blocks until a client sends a message bytesRead = clientStream.Read(message, 0, 4096); } catch(Exception ex) { //a socket error has occured //Console.WriteLine(ex.Message); break; } if (bytesRead == 0) { Console.WriteLine("Client @[{0}] disconnect @{1}", tcpClient.Client.LocalEndPoint, DateTime.Now.ToString()); break; } ASCIIEncoding encoder = new ASCIIEncoding(); string recvstr = encoder.GetString(message, 0, bytesRead); if (recvstr.StartsWith("GET")) { Console.WriteLine("响应GET"); string content = "HTTP/1.1 200 OK\r\n" + "Date: Mon, 27 Jul 2009 12:28:53 GMT\r\n" + "Server: ApacheLast-Modified: Wed, 22 Jul 2009 19:15:56\r\n" + "GMTETag: \"34aa387-d-1568eb00\"\r\nAccept-Ranges: bytes\r\n" + "Content-Type: text/html;charset=UTF-8\r\n\r\n" + "<!DOCTYPE html>\r\n<html lang=\"en\">\r\n<head>\r\n" + "<meta charset=\"UTF-8\">\r\n<meta http-equiv='Content-Type' content='text/html'; charset='GB2312'/>\r\n" + "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\r\n<title>tcp_to_http</title>\r\n" + "</head>\r\n<body>\r\n<p><label class='LeftLabel'>name:</label>\r\n" + "<input type='text' id='meterName' name='meterName' size='16' value=\"25231235\"/>\r\n" + "</p>\r\n<script>\r\nsetInterval('updateWeightState()',2000);\r\nfunction updateWeightState()\r\n" + "{\r\nconst xhr = new XMLHttpRequest();\r\n" + "xhr.open('post','/updateWeightState'+document.getElementById('meterName').value);\r\n" + "xhr.send();\r\nxhr.onreadystatechange = function ()\r\n{\r\n" + "document.getElementById('meterName').value=\"rec\"+xhr.readyState+\",\"+xhr.status+\",\"+xhr.response;\r\n" + "}\r\n}\r\n</script>\r\n</body>\r\n</html>\r\n\r\n\r\n\r\n\r\n\r\n"; byte[] buffer = encoder.GetBytes(content); clientStream.Write(buffer, 0, buffer.Length); clientStream.Flush(); clientStream.Close(); } else if (recvstr.StartsWith("POST")) { Console.WriteLine("响应POST"); string content =""; content += "HTTP/1.1 200 OK"; content += "Date: Mon, 27 Jul 2009 12:28:53 GMT"; content += "Server: ApacheLast-Modified: Wed, 22 Jul 2009 19:15:56"; content += "GMTETag: \"34aa387-d-1568eb00\""; content += "Accept-Ranges: bytes"; content += "Content-Type: text/html;charset=UTF-8"; content += "Content-Length: 3\r\n\r\n"; content += "{uint=123}"; byte[] buffer = encoder.GetBytes(content); clientStream.Write(buffer, 0, buffer.Length); clientStream.Flush(); clientStream.Close(); } } tcpClient.Close(); } } }

本文作者:Kellermen

本文链接:

版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!