1. 程式人生 > >socket-WebSocket-HttpListener-TcpListener服務端客戶端的具體使用案例

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 TcpListener服務端

//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 TcpListener客戶端

//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;
//}