目前这版 效果不错,速度快很多
<code class="lang-c">TcpListener TcpListene;
private void Form1_Load(object sender, EventArgs e)
{
TcpListene = new TcpListener(IPAddress.Parse("192.168.1.101"), 8790);
TcpListene.Start();//开始监听
new Task(() =>
{
while (true)
{
NewClient(TcpListene.AcceptTcpClient());
}
}).Start();
}
long a = 0, b = 0, c = 0, d = 0, f = 0;
void NewClient(TcpClient BrowseService)//新客户端接入
{
TcpClient AgencyClient = new TcpClient();//链接到代理服务器
AgencyClient.Connect(IPAddress.Parse("127.0.0.1"), 8787);
var BrowserStream = BrowseService.GetStream();
var AgencyStream = AgencyClient.GetStream();
a++;
Task t1 = new Task(() =>
{
using (AgencyClient) using (BrowseService) using (AgencyStream) using (BrowserStream)
{
byte[] buffer = new byte[128];
int count = 0;
while (true)
{
try
{
if ((count = BrowserStream.Read(buffer, 0, buffer.Length)) == 0) break;
AgencyStream.Write(buffer, 0, count);
} catch (Exception) { d++; break; }
//Console.WriteLine(string.Format("Beowser -> Agency:{0}", Encoding.Default.GetString(buffer,0,count)));
}
b++;
}
});
t1.Start();
Task t2 = new Task(() =>
{
using (AgencyClient) using (BrowseService) using (AgencyStream) using (BrowserStream)
{
byte[] buffer = new byte[128];
int count = 0;
while (true)
{
try
{
if ((count = AgencyStream.Read(buffer, 0, buffer.Length)) == 0) break;
BrowserStream.Write(buffer, 0, count);
}
catch (Exception) { f++; break; }
//Console.WriteLine(string.Format("Agency -> Beowser:{0}", Encoding.Default.GetString(buffer, 0, count)));
}
c++;
}
});
t2.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
this.Invoke(new Action(()=>{
label1.Text = string.Format("全部创建socket:{0}个\r\n关闭了socket:{2}个\r\n现有socke:{1}个\r\nb={3}个\r\nc={4}\r\nd={5}\r\nf={6}", a, a - (b + c)/2, (b + c)/2, b, c, d, f);
}));
}</code>