TcpListener类的应用:只能接收一次内容!
在本机的2000端口监听客户端连接,然后在页面上显示传送的文件内容;
问题如下:第一次传送是可以显示的;但是不能连续显示第二次传入的内容?
请教高手指点一下,谢谢!
代码如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.IO;
namespace TcpReceiver
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Thread thread = new Thread(new ThreadStart(Listen));
thread.Start();
}
protected void Listen()
{
try
{
// IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
IPAddress ipAddress = IPAddress.Any;
Int32 port = 2000;
TcpListener tcpListener = new TcpListener(ipAddress, port);
tcpListener.Start();
//TcpClient tcpClient = tcpListener.AcceptTcpClient(); 这里是同步调用会阻塞后面的请求
tcpListener.BeginAcceptTcpClient(new AsyncCallback(AcceptClient), tcpListener);
//这里采用异步调用,接收一个连接请求,就开启一个线程来处理请求
}
catch (Exception ex)
{
MessageBox.Show("出错了: \n" + ex.Message, "错误");
}
}
protected void AcceptClient(IAsyncResult ar)
{
try
{
TcpListener tcpListener = (TcpListener)ar.AsyncState;
TcpClient tcpClient = tcpListener.EndAcceptTcpClient(ar);
NetworkStream networkStream = tcpClient.GetStream();
StreamReader streamReader = new StreamReader(networkStream);
string content = streamReader.ReadToEnd();
rtbxContent.Invoke(new MethodInvoker(delegate
{
rtbxContent.Text = "";
rtbxContent.Text = content;
}));
networkStream.Close();
tcpClient.Close();
//tcpListener.Stop();
}
catch (Exception ex)
{
MessageBox.Show("出错了: \n" + ex.Message, "错误");
}
}
}
}
------解决方案--------------------
你先new一个Thread,在里面:
C# code
while()
{
Socket socket = tcplistener.AcceptSocket();
if (socket != null)
StartItem(socket);
}
------解决方案--------------------
你这个Listen和AcceptClient的方法也就被执行了一次吧,里面也没有while循环取读取数据,读了一次,就结束线程了
------解决方案--------------------
TcpListener tcpListener = (TcpListener)ar.AsyncState;
TcpClient tcpClient = tcpListener.EndAcceptTcpClient(ar);
while (true)
{。。。。。
----求分