using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading;
namespace MultiClientServer
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
TcpListener listner = new TcpListener(new IPEndPoint(IPAddress.Loopback, 8000));
listner.Start();
textBox1.Text += "Started TCP Server"+Environment.NewLine;
listner.BeginAcceptTcpClient(new AsyncCallback(Accept), listner);
}
void Accept(IAsyncResult result)
{
textBox1.Invoke(new MethodInvoker(delegate()
{
textBox1.Text += "Client Request Arrived" + Environment.NewLine;
}));
TcpListener listner1 = (TcpListener)result.AsyncState;
TcpClient client = listner1.EndAcceptTcpClient(result);
textBox1.Invoke(new MethodInvoker(delegate()
{
textBox1.Text += "Client Request Approved" + Environment.NewLine;
}));
Thread th = new Thread(new ParameterizedThreadStart(ContinueRcv));
th.Start(client);
}
void ContinueRcv(object obj)
{
TcpClient client = (TcpClient)obj;
StreamReader sr = new StreamReader(client.GetStream());
textBox1.Invoke(new MethodInvoker(delegate()
{
textBox1.Text += sr.ReadLine() + Environment.NewLine;
}));
}
}
}
我试着制作这个应用程序,这样当客户端连接超过一个新线程时,就会创建b,并且它会在继续接收b。不幸的是..。请用这段代码给我解决方案。意味着这不是一个阶级的要求什么的。我想知道如何用这个或任何相关的方式来做这件事。
发布于 2014-03-15 07:20:38
线程不是不断调用的东西,线程块中的代码需要不断调用,因为您的线程负责调用ContinueRcv
--线程以该方法的结尾结束,
如果要连续地从Stream
接收数据,则需要在无限循环中调用StreamReader的ReadLine(),
void ContinueRcv(object obj)
{
TcpClient client = (TcpClient)obj;
StreamReader sr = new StreamReader(client.GetStream());
while (true)
{
if ( !connection ) { // when connection closed, abort, terminated
break;
}
msg = sr.ReadLine();
textBox1.Invoke(new MethodInvoker(delegate()
{
textBox1.Text += msg + Environment.NewLine;
}));
}
}
当连接关闭时,请记住断开循环,
https://stackoverflow.com/questions/22252159
复制相似问题