写一个小型的,只有接收和发送消息的HTTP服务器
有时候我们要写通信模块,写完之后总要测测通不通吧。我不知道别人是怎么做的,但是我自己觉得,要不写个小型服务器(程序?),只能接收和发送消息就行了,于是就上网翻了下,好像并没有现成的代码(叹气),还是自己写一个吧。
HTTP也是Tcp通信,上篇文章的Tcp服务器端其实拿过来用就行了,只是出了点小问题导致无法正常返回,所以写下来记录一下,希望以后更细心,别再犯类似错误。
- using System;
- using System.Collections;
- using System.IO;
- using System.Net;
- using System.Net.Sockets;
- using System.Threading;
- using System.Text;
- namespace TestServer
- {
- public class MyHttpServer
- {
- string ip;
- int port;
- TcpListener listener;
- StreamWriter outStream;
- TcpClient remoteClient;
- NetworkStream ClientStream;
- public MyHttpServer(string inip,int inport)
- {
- ip = inip;
- port = inport;
- }
- public void listen()
- {
- listener = new TcpListener(IPAddress.Parse(ip),port);
- listener.Start();
- Console.WriteLine(“监听启动!”);
- byte[] buffer = new byte[1024];
- while (true)
- {
- try
- {
- remoteClient = listener.AcceptTcpClient();//阻塞
- Console.WriteLine(“有客户端进入!”);
- ClientStream = remoteClient.GetStream();
- int byteRead = ClientStream.Read(buffer, 0, 1024);
- if (byteRead == 0)
- {
- Console.WriteLine(“没东西啊!!”);
- continue;
- }
- string msg = Encoding.UTF8.GetString(buffer, 0, byteRead);
- Console.WriteLine(“接收数据:” msg);
- string head = “”;
- char [] charArray = Encoding.UTF8.GetChars(buffer);
- int i = 0;
- while(!charArray[i].Equals(‘ ‘))
- {
- head = charArray[i];
- i;
- }
- Console.WriteLine(head);
- switch (head)
- {
- case “POST”:
- {
- string msg2 = “这是POST方法”;
- byte[] buffer2 = Encoding.UTF8.GetBytes(msg2);//将字符串转化为二进制
- ClientStream.Write(buffer2, 0, buffer2.Length);//将转换好的二进制数据写入流中并发送
- remoteClient.Close();//问题就出在这里,一定要关闭
- }
- break;
- case “GET”:
- {
- string msg2 = “这是GET方法”;
- byte[] buffer2 = Encoding.UTF8.GetBytes(msg2);
- ClientStream.Write(buffer2, 0, buffer2.Length);
- remoteClient.Close();//问题就出在这里,一定要关闭
- }
- break;
- }
- }
- catch (Exception ex)
- {
- Console.WriteLine(“异常:” ex.Message);
- break;
- }
- };
- }
- }
- class Program
- {
- static void Main(string[] args)
- {
- Console.WriteLine(“Hello World!”);
- Console.WriteLine(“—————————————“);
- MyHttpServer server = new MyHttpServer(“127.0.0.1”,8080);
- Thread thread = new Thread(new ThreadStart(server.listen));
- thread.Start();
- }
- }
- }
remoteClient.Close();就因为这里没写,客户端发的消息能收到,但是一直得不到反馈,而客户端打开的情况下,退出服务端,客户端才会接受到反馈,当然,是空的。
以后要多加注意,Tcp是连接性的通讯,服务端接受消息后如果不手动关闭连接,系统默认为连接并未断开,也就不会将消息返回。
另外,话说我明明是做C 的,怎么贴的都是C#代码,emmmmm…..