socket-WebSocket-HttpListener-TcpListener服务端客户端的具体使用案例

Posted LongtengGensSupreme

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了socket-WebSocket-HttpListener-TcpListener服务端客户端的具体使用案例相关的知识,希望对你有一定的参考价值。

/// <summary>
/// 启动服务监听的ip和端口的主线程
/// </summary>
/// <param name="tunnelPort"></param>
public void StartService(int tunnelPort)
{
Port = tunnelPort;
Encoding = Encoding.UTF8;
ListeningThread = new Thread(new ThreadStart(StartListening));
ListeningThread.IsBackground = Environment.OSVersion.Platform != PlatformID.Unix;//
ListeningThread.Start();

}

internal void StartListening()
{
#region socket服务端
//int port = 1234;
//string host = "127.0.0.1";

//IPAddress ip = IPAddress.Parse(host);
//IPEndPoint ipe = new IPEndPoint(ip, port);

//Socket sSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//sSocket.Bind(ipe);
//sSocket.Listen(0);
//Console.WriteLine("监听已经打开,请等待");

////receive message
//Socket serverSocket = sSocket.Accept();
//Console.WriteLine("连接已经建立");
//string recStr = "";
//byte[] recByte = new byte[4096];
//int bytes = serverSocket.Receive(recByte, recByte.Length, 0);
//recStr += Encoding.ASCII.GetString(recByte, 0, bytes);

//////send message
//Console.WriteLine("服务器端获得信息:{0}", recStr);
//string sendStr = "send to client :hello";
//byte[] sendByte = Encoding.ASCII.GetBytes(recStr);
//serverSocket.Send(sendByte, sendByte.Length, 0);
//serverSocket.Close();
//sSocket.Close();

#endregion

#region socket客户端
//int port = 1234;
//string host = "127.0.0.1";//服务器端ip地址

//IPAddress ip = IPAddress.Parse(host);
//IPEndPoint ipe = new IPEndPoint(ip, port);

// Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//clientSocket.Connect(ipe);

////send message
//string sendStr = "begin#70";
//byte[] sendBytes = Encoding.ASCII.GetBytes(sendStr);
//clientSocket.Send(sendBytes);

////receive message
//string recStr = "";
//byte[] recBytes = new byte[4096];
//int bytes = clientSocket.Receive(recBytes, recBytes.Length, 0);
//recStr += Encoding.ASCII.GetString(recBytes, 0, bytes);
//Console.WriteLine(recStr);

//clientSocket.Close();
#endregion

#region Http服务端
//HttpListener listener = new HttpListener();
////listener.Prefixes.Add("http://*:8080/");
//listener.Prefixes.Add("http://+:" + 1234 + "/");
//listener.Start();

//while (true)
//{
// IAsyncResult result = listener.BeginGetContext(new AsyncCallback(ListenerCallback), listener);
// result.AsyncWaitHandle.WaitOne();
//}
#endregion

#region Http客户端
//HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + (postDataStr == "" ? "" : "?") + postDataStr);
//request.Method = "GET";
//request.ContentType = "text/html;charset=UTF-8";

//HttpWebResponse response = (HttpWebResponse)request.GetResponse();
//Stream myResponseStream = response.GetResponseStream();
//StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
//string retString = myStreamReader.ReadToEnd();//返回结果
//myStreamReader.Close();
//myResponseStream.Close();
#endregion

#region WebSocket服务端 4.0方式,不适合win7 系统,适合win8,win10 ,win server 2008,win server 2012等高版本系统
//HttpListener listener = new HttpListener();
////listener.Prefixes.Add("http://*:8080/");
//listener.Prefixes.Add("http://+:" + 1234 + "/");
//listener.Start();

//var context = listener.GetContextAsync();
//var wsContext = context.Result.AcceptWebSocketAsync("");
//var ws = wsContext.Result.WebSocket;
//接受客户端发来的消息
//处理客户端发来的消息,处理完成之后,发给客户端消息
#endregion

#region WebSocket客户端 4.0方式,不适合win7 系统,适合win8,win10 ,win server 2008,win server 2012等高版本系统

// string url = "ws://127.0.0.1:1234/";
// try
// {
// ClientWebSocket cln = new ClientWebSocket();
// cln.ConnectAsync(new Uri(url), new CancellationToken()).Wait();

// byte[] bytess = Encoding.Default.GetBytes("begin#70");
// cln.SendAsync(new ArraySegment<byte>(bytess), WebSocketMessageType.Text, true, new CancellationToken()).Wait();
// byte[] bytes2 = new byte[1000 * 500];
// //var webSocketReceiveResult = cln.ReceiveAsync(new ArraySegment<byte>(bytes2), CancellationToken.None);

// //GetAsyncValue(cln);//异步方法,很关键
// string returnValue = await GetAsyncValue(cln);//异步方法
// //string xx = Encoding.Default.GetString(bytes2);

// Console.Read();
// }
//catch
//{
// Thread.Sleep(1000);
//}
#endregion

#region Tcp服务端

//TcpListener tcpListener = null;
//int port = 22333;
//string host = "127.0.0.1";
//IPAddress ip = IPAddress.Parse(host);
//IPEndPoint ipe = new IPEndPoint(ip, port);
//tcpListener = new TcpListener(ipe);
//tcpListener.Start();

//try
//{
// Byte[] bytes = new Byte[1024];
// String data = null;
// while (true)
// {
// Console.Write("Waiting for a connection... ");
// TcpClient client = tcpListener.AcceptTcpClient();
// Console.WriteLine("Connected!");
// data = null;

#region MyRegion
//NetworkStream stream = client.GetStream();
//int i = stream.Read(bytes, 0, bytes.Length);
//data = Encoding.Default.GetString(bytes, 0, i);
//Console.WriteLine("Received: {0}", data);
//byte[] msg = Encoding.Default.GetBytes(data + "ok");
//stream.Write(msg, 0, msg.Length);
//Console.WriteLine("Sent: {0}", data);
#endregion
// NetworkStream stream = client.GetStream();
// int i;
// while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
// {
// data += Encoding.Default.GetString(bytes, 0, i);
// Console.WriteLine("Received: {0}", data);
// byte[] msg = Encoding.Default.GetBytes(data + "ok");
// stream.Write(msg, 0, msg.Length);
// Console.WriteLine("Sent: {0}", data);
// }
// client.Close();
// }
//}
//catch (Exception e)
//{
//}
#endregion

#region Tcp客户端

//TcpClient tcpClient = new TcpClient("127.0.0.1", 22333);
//NetworkStream stream = tcpClient.GetStream();
//byte[] seb = System.Text.Encoding.Default.GetBytes("222222222222");
//stream.Write(seb, 0, seb.Length);

//byte[] seb2 = new byte[1024];
//int xx = stream.Read(seb2, 0, seb2.Length);
//string returnValue = Encoding.Default.GetString(seb2, 0, xx);
//stream.Close();
//tcpClient.Close();

#endregion


}

internal void StartListening1()
{
TcpListener tcpListener = null;
int port = 22333;
string host = "127.0.0.1";
IPAddress ip = IPAddress.Parse(host);
IPEndPoint ipe = new IPEndPoint(ip, port);
tcpListener = new TcpListener(ipe);
tcpListener.Start();

try
{
Byte[] bytes = new Byte[1024];
String data = null;
while (true)
{
Console.Write("Waiting for a connection... ");
TcpClient client = tcpListener.AcceptTcpClient();
Console.WriteLine("Connected!");
data = null;
NetworkStream stream = client.GetStream();
int i = stream.Read(bytes, 0, bytes.Length);
data = Encoding.Default.GetString(bytes, 0, i);
Console.WriteLine("Received: {0}", data);
byte[] msg = Encoding.Default.GetBytes(data + "ok");
stream.Write(msg, 0, msg.Length);
Console.WriteLine("Sent: {0}", data);
//while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
//{
// data += Encoding.Default.GetString(bytes, 0, i);
// Console.WriteLine("Received: {0}", data);
// byte[] msg = Encoding.Default.GetBytes(data + "ok");
// stream.Write(msg, 0, msg.Length);
// Console.WriteLine("Sent: {0}", data);
//}
client.Close();
}
}
catch (Exception e)
{
}
}

private void ListenerCallback(IAsyncResult result)
{
HttpListener listener = (HttpListener)result.AsyncState;
HttpListenerContext context = listener.EndGetContext(result);
processRequest(context);

}

private void processRequest(HttpListenerContext context)
{
HttpListenerRequest request = context.Request;
try
{
//string url = System.Web.HttpUtility.UrlDecode(request.RawUrl);
string ss = request.QueryString["eid"];
context.Response.ContentEncoding = UTF8Encoding.UTF8;
context.Response.Headers.Add("Access-Control-Allow-Origin", "*");
//context.Response.ContentType = "image/jpg";
//context.Response.ContentLength64 = buffer.Length;
var output = context.Response.OutputStream;
byte[] nn = System.Text.Encoding.Default.GetBytes("qqqqqqqqqqqq");
output.Write(nn, 0, nn.Length);
output.Close();
}
catch (Exception e)
{

}
finally
{
}
}

//异步方法
//public static async Task<string> GetAsyncValue(ClientWebSocket clientWebSocket)
//{
// string returnValue = null;
// ArraySegment<Byte> buffer = new ArraySegment<byte>(new Byte[8192]);
// WebSocketReceiveResult result = null;
// using (var ms = new MemoryStream())
// {
// do
// {
// result = await clientWebSocket.ReceiveAsync(buffer, CancellationToken.None);
// ms.Write(buffer.Array, buffer.Offset, result.Count);
// }
// while (!result.EndOfMessage);
// ms.Seek(0, SeekOrigin.Begin);
// if (result.MessageType == WebSocketMessageType.Text)
// {
// using (var reader = new StreamReader(ms, Encoding.UTF8))
// {
// returnValue = reader.ReadToEnd();
// //Console.WriteLine(returnValue);
// }
// }
// }
// return returnValue;
//}































































































































































































































以上是关于socket-WebSocket-HttpListener-TcpListener服务端客户端的具体使用案例的主要内容,如果未能解决你的问题,请参考以下文章