zoukankan
html css js c++ java
C# server socket 异步编程
using
System;
using
System.Collections.Generic;
using
System.Text;
using
System.Net;
using
System.Net.Sockets;
using
System.Threading;
namespace
ScoketProxy
{
class
ZServer
{
ManualResetEvent clientConnected
=
new
ManualResetEvent(
false
);
TcpListener tl;
public
ZServer(
int
port)
{
tl
=
new
TcpListener(port);
}
~
ZServer()
{
tl.Stop();
}
public
void
Listen()
{
tl.Start(
5
);
clientConnected.Reset();
while
(
true
)
{
tl.BeginAcceptTcpClient(
new
AsyncCallback(OnAccept), tl);
clientConnected.WaitOne();
}
}
void
OnAccept(IAsyncResult ar)
{
TcpListener listener
=
(TcpListener)ar.AsyncState;
TcpClient client
=
listener.EndAcceptTcpClient(ar);
TcpClient tranform
=
new
TcpClient(
"
220.181.5.97
"
,
80
);
NetworkStream cns
=
client.GetStream();
NetworkStream tns
=
tranform.GetStream();
while
(client.Connected)
{
//
byte[] cbuf = ReadBlock(client);
//
tns.Write(cbuf, 0, cbuf.Length);
//
byte[] tbuf = ReadBlock(tranform);
//
cns.Write(tbuf,0,tbuf.Length);
byte
[] cbuf
=
ReadBlock(client);
SendBlock(client, cbuf);
byte
[] tbuf
=
ReadBlock(tranform);
SendBlock(tranform, tbuf);
}
//
TcpListener listener = (TcpListener)ar.AsyncState;
//
TcpClient client = listener.EndAcceptTcpClient(ar);
//
clientConnected.Set();
//
while(true)
//
{
//
string s = ReadLine(client);
//
if (s == "exit")
//
{
//
Console.WriteLine("bye");
//
break;
//
}
//
byte[] buf = GetBytes(s);
//
client.GetStream().Write(buf,0,buf.Length);
//
}
//
return;
}
byte
[] GetBytes(
string
s)
{
return
System.Text.Encoding.UTF8.GetBytes(s.ToCharArray());
}
string
GetString(
byte
[] bs)
{
return
System.Text.Encoding.UTF8.GetString(bs);
}
string
ReadLine(TcpClient client)
{
StringBuilder sb
=
new
StringBuilder();
NetworkStream ns
=
client.GetStream();
while
(
true
)
{
byte
[] buf
=
new
byte
[client.Available];
ns.Read(buf,
0
, buf.Length);
string
s
=
GetString(buf);
if
(s
==
"
\r\n
"
)
{
break
;
}
sb.Append(s);
}
return
sb.ToString();
}
byte
[] ReadBlock(TcpClient client)
{
System.Collections.Generic.List
<
byte
>
r
=
new
List
<
byte
>
();
while
(client.GetStream().DataAvailable)
{
byte
[] buf
=
new
byte
[
1
];
client.GetStream().Read(buf,
0
, buf.Length);
r.Add(buf[
0
]);
}
return
r.ToArray();
}
int
SendBlock(TcpClient c,
byte
[] buf)
{
c.GetStream().Write(buf,
0
, buf.Length);
return
buf.Length;
}
}
}
查看全文
相关阅读:
洛谷P1622 释放囚犯(dp好题)
精灵魔法(vector逆序对,离散化数状数组)
十大排序方法
线段树总结(萌新必看)
【BZOJ4145】[AMPPZ2014]The Prices 状压dp
TJOI2013 奖学金—大根堆实现(洛谷P3963)
APIO强掠计划(spfa+tarjan缩点)
火车运输(最大生成树+lca) 洛谷P1967
计算机网络基础知识总结(二)
测试用例--“好的”测试用例
原文地址:https://www.cnblogs.com/zyip/p/1450590.html
最新文章
我对递归的理解(适合新手)
动态规划解题(leetcode322零钱兑换)
C/C++实现快速排序的两种典型代码
动态规划---01背包问题(1)
习题5-6 使用函数输出水仙花数
习题5-5 使用函数统计指定数字的个数
简单的电脑使用和维护方法(肝货一)
Host是什么?如何设置host文件?
Linux桌面进化史
如何(正确)使用搜索引擎?使用搜索引擎的高效技巧(例如:百度、谷歌)
热门文章
Windows注册表内容详解
记Centos7和RHEL连接不上网络
如何更换Windows中命令提示符(cmd)中的字体
JAVA基础笔记10-11-12-13-14
简单认识JAVA内存划分
计算机网络知识梳理
MySQL常规操作
如何Simplest搭建个人博客
MySQL命令
Java基础笔记05-06-07-08
Copyright © 2011-2022 走看看