寫一個(gè)小型的,只有接收和發(fā)送消息的HTTP服務(wù)器
有時(shí)候我們要寫通信模塊,寫完之后總要測(cè)測(cè)通不通吧。我不知道別人是怎么做的,但是我自己覺得,要不寫個(gè)小型服務(wù)器(程序?),只能接收和發(fā)送消息就行了,于是就上網(wǎng)翻了下,好像并沒有現(xiàn)成的代碼(嘆氣),還是自己寫一個(gè)吧。
HTTP也是Tcp通信,上篇文章的Tcp服務(wù)器端其實(shí)拿過來用就行了,只是出了點(diǎn)小問題導(dǎo)致無法正常返回,所以寫下來記錄一下,希望以后更細(xì)心,別再犯類似錯(cuò)誤。
- 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(“監(jiān)聽啟動(dòng)!”);
- byte[] buffer = new byte[1024];
- while (true)
- {
- try
- {
- remoteClient = listener.AcceptTcpClient();//阻塞
- Console.WriteLine(“有客戶端進(jìn)入!”);
- ClientStream = remoteClient.GetStream();
- int byteRead = ClientStream.Read(buffer, 0, 1024);
- if (byteRead == 0)
- {
- Console.WriteLine(“沒東西啊?。?#8221;);
- continue;
- }
- string msg = Encoding.UTF8.GetString(buffer, 0, byteRead);
- Console.WriteLine(“接收數(shù)據(jù):” 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);//將字符串轉(zhuǎn)化為二進(jìn)制
- ClientStream.Write(buffer2, 0, buffer2.Length);//將轉(zhuǎn)換好的二進(jìn)制數(shù)據(jù)寫入流中并發(fā)送
- remoteClient.Close();//問題就出在這里,一定要關(guān)閉
- }
- break;
- case “GET”:
- {
- string msg2 = “這是GET方法”;
- byte[] buffer2 = Encoding.UTF8.GetBytes(msg2);
- ClientStream.Write(buffer2, 0, buffer2.Length);
- remoteClient.Close();//問題就出在這里,一定要關(guān)閉
- }
- 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();就因?yàn)檫@里沒寫,客戶端發(fā)的消息能收到,但是一直得不到反饋,而客戶端打開的情況下,退出服務(wù)端,客戶端才會(huì)接受到反饋,當(dāng)然,是空的。
以后要多加注意,Tcp是連接性的通訊,服務(wù)端接受消息后如果不手動(dòng)關(guān)閉連接,系統(tǒng)默認(rèn)為連接并未斷開,也就不會(huì)將消息返回。
另外,話說我明明是做C 的,怎么貼的都是C#代碼,emmmmm…..