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服务端客户端的具体使用案例的更多相关文章
- socket-WebSocket HttpListener TcpListener 服务端客户端的具体使用案例
/// <summary>/// 启动服务监听的ip和端口的主线程/// </summary>/// <param name="tunnelPort" ...
- WebSocket——SuperWebSocket实现服务端和客户端
WebSocket——SuperWebSocket实现服务端和客户端具体实现如下: 注:本作者是基于vs2019 enterprise版本,所有项目均为.Net Framwork4.7版本(因为Web ...
- 客户端 new socket时候 就像服务端发起连接了
客户端 new socket时候 就像服务端发起连接了
- TCP Socket服务端客户端(二)
本文服务端客户端封装代码转自https://blog.csdn.net/zhujunxxxxx/article/details/44258719,并作了简单的修改. 1)服务端 此类主要处理服务端相关 ...
- PHP-Socket服务端客户端发送接收通信实例详解
原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 .作者信息和本声明.否则将追究法律责任.http://fighter.blog.51cto.com/1318618/1533957 So ...
- TCP/IP网络编程之基于UDP的服务端/客户端
理解UDP 在之前学习TCP的过程中,我们还了解了TCP/IP协议栈.在四层TCP/IP模型中,传输层分为TCP和UDP这两种.数据交换过程可以分为通过TCP套接字完成的TCP方式和通过UDP套接字完 ...
- TCP/IP网络编程之基于TCP的服务端/客户端(二)
回声客户端问题 上一章TCP/IP网络编程之基于TCP的服务端/客户端(一)中,我们解释了回声客户端所存在的问题,那么单单是客户端的问题,服务端没有任何问题?是的,服务端没有问题,现在先让我们回顾下服 ...
- TCP/IP网络编程之基于TCP的服务端/客户端(一)
理解TCP和UDP 根据数据传输方式的不同,基于网络协议的套接字一般分为TCP套接字和UDP套接字.因为TCP套接字是面向连接的,因此又称为基于流(stream)的套接字.TCP是Transmissi ...
- 使用tomcat方式实现websocket即时通讯服务端讲解
使用tomcat方式实现websocket即时通讯服务端讲解 第一种方案:使用Tomcat的方式实现 tomcat版本要求:tomcat7.0+.需要支持Javaee7 导入javeee-api的ja ...
随机推荐
- 三、文件IO——系统调用(续)
3.2.4 read 函数--- 读文件 read(由已打开的文件读取数据) #include<unistd.h> ssize_t read(int fd, void * buf, siz ...
- 【python小练】0004
第 0004 题:任一个英文的纯文本文件,统计其中的单词出现的个数. 先回忆一下各种括号的用途: () tuple [] list {} dict ([]) set——需要一个list作为输入合集 c ...
- Debian Security Advisory(Debian安全报告) DSA-4406-1 waagent
Package : waagentCVE ID : CVE-2019-0804 Francis McBratney发现Windows Azure Linux代理创建了具有 ...
- pyqt5-顶层窗口特定操作-图标和标题和不透明度
图标: setWindowIcon(QIcon("resource/header_icon.png")) 设置窗口图标 icon=QIcon(r'大象.png') ...
- linux一些比较重要的环境变量。配置文件
永久添加环境变量PATH 方法一:编辑/etc/profile.d/NAME.sh 写入这句话export PATH=/PATH/TO/SOMEWHRER:$PATH 永久修改动态库文件搜索路径 方法 ...
- MySql cmd下的学习笔记 —— 有关表的操作(对表中数据的增,删,改,查)
(知识回顾) 连接数据库 mysql -uroot -p111 先建立一个新库 create database test1; use test1; 由于今天的主要内容是表的操作,建立表的详细过程不是本 ...
- HDOJ 4267 A Simple Problem with Integers (线段树)
题目: Problem Description Let A1, A2, ... , AN be N elements. You need to deal with two kinds of opera ...
- 1.Linux电源管理-休眠与唤醒【转】
转自:https://www.cnblogs.com/lifexy/p/9629699.html 1.休眠方式 在内核中,休眠方式有很多种,可以通过下面命令查看 # cat /sys/power/st ...
- sort和uniq去重操作【转】
去除重复行 sort file |uniq 查找非重复行 sort file |uniq -u 查找重复行 sort file |uniq -d 统计 sort file | uniq - ...
- vc++基础班[24]---系统各种路径信息的获取
vc++基础班[24]---系统各种路径信息的获取 ------------------------------------------ Begin ------------------------- ...