server=tmpserver
//然后新建一个进程,对server进行通信操作
实际还是操作的tmpserver异步=同步+多线程
//然后新建一个进程,对server进行通信操作
实际还是操作的tmpserver异步=同步+多线程
解决方案 »
- 发现一个bug textbox对size限制没有效果
- C# 关于绑定事件的问题
- 屏幕分辨率变了 程序也跟着变化 高分求方法============================================>
- 复制table的row的问题::无法将类型为“System.Data.DataRow”的对象强制转换为类型“System.IConvertible”。
- C#如何判断打印机缺纸?
- rdlc报表中页面设置的问题
- pictureBox1_LocationChanged事件
- 一个datalist嵌套RadioButton1问题----再开帖子问一下朋友们
- 有没有ASP.net的数据生成器?
- 在vc#.net那里有多文档窗体
- 主机通过TcpListener.AcceptTcpClient()方法接受客户端连接,怎么才能得到客户端的IP
- 語法問題-派生類繼承多個父類 怎麼寫?
t.Start();
我是新建了一个类了,怎么还会是一样??
t.Start();这个我知道,我上面的代码只是大概写一下,我只要是想问我这个实现方法行不行??
{
private TcpListener server;
private bool isserver;
private Thread thread; pubic Test()
{
int port = 13000;
IPAddress localAddr = IPAddress.Parse("127.0.0.1");
this.server = new TcpListener(localAddr, port);
this.thread = new Thread(new ThreadStart(this.Start));
} //开始异步监听请求
public void StartServer()
{
this.isserver=true;
this.thread.Start();
} //停止监听
public void StopServer()
{
this.isserver=false;
this.thread.Abort();
} private void Start()
{
this.server.Start();
while(this.isserver)
{
TcpClient client=this.server.AcceptTcpClient();
new Thread(new ThreadStart(new HandleRequest(client))).Start();
}
}
}pubic class HandleRequest
{
private TcpClient client; public HandleRequest(TcpClient client)
{
this.client = client;
} public void Handle()
{
this.client.GetStream().Read(...);
...
//在这里处理请求
}
}
new Thread(new ThreadStart(new HandleRequest(client))).Start();会为每个连接生成一个TcpClient对象并异步处理之!
是什么时候调用的????
BeginXXX、EndXXX之间哪些关系又是怎样的??不是说用异步发送数据要用这些的吗?
应该是调用tmpserver.Start()后,用while循环取队列中的传入连接进行处理:
public static void Main()
{
try
{
Int32 port = 13000;
IPAddress localAddr = IPAddress.Parse("127.0.0.1");
TcpListener server = new TcpListener(localAddr, port);
server.Start();
while(true)
{
TcpClient client = server.AcceptTcpClient();//获取队列中的传入连接
//对该连接进行处理
//...
client.Close();
}
}
catch(SocketException ex)
{
MessageBox.Show(ex.Message);
}
}
2、StopServer()在你的服务程序停止监听请求的时候调用
3、Handle()不用你显示调用,当你的服务程序监听到客户端请求后会自行调用,你要做的是在Handle()方法中写入与客户端通讯的逻辑!try it
我试了,编译下面一条时,因为ThreadStart的参数只用方法,所以提示错误
new Thread(new ThreadStart(new HandleRequest(client))).Start();
还有还是不明为什么Handle()会自动调用??
to: losthold(呵呵)
MSDN的例子不完整的,只是针对说一部分,没有总体来说,所以看不懂!!
把
new Thread(new ThreadStart(new HandleRequest(client))).Start();
改成
new Thread(new ThreadStart(new HandleRequest(client).Handle)).Start();这下你明白为什么Handle()会自动调用了吧?