使用监听功能,输出一个Web功能
代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Threading;
namespace Listener
{
class Program
{
private static Thread th;//线程
private static TcpListener tcpl;//监听
public static bool listenerrunning = true;
/// <summary>
/// 主程序
/// </summary>
/// <param name="args"></param>
static void Main(string[] args)
{
th = new Thread(new ThreadStart(listener));
th.Start();
}
/// <summary>
/// 启动监听端口
/// </summary>
public static void listener()
{
try
{
tcpl = new TcpListener(5566);
tcpl.Start();
Console.WriteLine("监听端口5566开始.......");
while (listenerrunning)
{
Socket s = tcpl.AcceptSocket();
string remote = s.RemoteEndPoint.ToString();
Byte[] stream = new Byte[80];
int i = s.Receive(stream);//接受连接请求的字节流
string msg = "<" + remote + ">" + System.Text.Encoding.UTF8.GetString(stream);
StringBuilder buf = new StringBuilder();
#region================================输入http报头============================================================
buf.Append("HTTP/1.1 200 OK\r\n");
buf.Append("Content-Type: text/html\r\n");//html返回
//buf.Append("Content-Type: text/xml\r\n");//xml返回
buf.Append("Accept-Ranges: bytes\r\n");
buf.Append("Content-Length: 38\r\n");
buf.Append("\r\n");
#endregion
buf.Append("<html><body>hello world </body></html>");
s.Send(System.Text.Encoding.UTF8.GetBytes(buf.ToString()));
Console.WriteLine(msg);//在控制台显示字符串
}
}
catch (Exception e)
{
stop();
throw e;
}
}
/// <summary>
/// 取消监听和线程
/// </summary>
public static void stop()
{
listenerrunning = false;
tcpl.Stop();
th.Abort();
}
}
}
效果如下: