把监听放到监听按钮内
============================
接收端:
监听函数:
public TcpListener listener;//定义一个监听
private void Listen()
{
socket = listener.AcceptSocket();
while(true)
{
string strTxt = string.Empty;
strTxt = CommunicationBase.ReadTextFromSocket(socket lbReceiveMessage.Items.Add( strTxt);
}
}
监听按钮:
private void btnIntercept_Click(object sender, System.EventArgs e)
{
listener = new TcpListener(Int32.Parse(txtClientPort.Text)); //<-
listener.Start(); //<-
Thread th = new Thread(new ThreadStart(Listen));
th.Start();
}
============================
接收端:
监听函数:
public TcpListener listener;//定义一个监听
private void Listen()
{
socket = listener.AcceptSocket();
while(true)
{
string strTxt = string.Empty;
strTxt = CommunicationBase.ReadTextFromSocket(socket lbReceiveMessage.Items.Add( strTxt);
}
}
监听按钮:
private void btnIntercept_Click(object sender, System.EventArgs e)
{
listener = new TcpListener(Int32.Parse(txtClientPort.Text)); //<-
listener.Start(); //<-
Thread th = new Thread(new ThreadStart(Listen));
th.Start();
}
解决方案 »
- 代码为什么不执行啊?
- 求一个C# 读写ini配置文件 的源码
- 讨论:C#跨数据库操作
- 对文件读写,能不创建两个stream,一个StreamReader,StreamWriter
- 救命!CE.NET中如何编写TCP通信程序?
- c# 使用webservice是有500错误
- 奇怪问题:把一个textBox绑定到自己创建的数据表中的一个字段,在程序里赋值给textBox,但表中的值却是空的
- C#中默认的方法参数类型是引用类型吗?
- 开心版主,能否告知你的那个支持认证的SMTP组件的帮助文档是用什么做的?
- 怎么提升循环的速度呢
- 本人最近接手一项目,在ie中打开mht文件的时候系统提示语法错误。在低版本的ie上却没有这个问题!
- 求教,怎么调用记事本?
你的程序逻辑有问题:
你的btnSend_Click()事件,每点击一下,都是建立一个新的对象,就是说从头建立连接等网络操作,
而 你的侦听函数,是先socket = listener.AcceptSocket(); //接受刮起的连接请求,当客户端来了一个请求时,此举响应,以后进入while(),当客户端二度连接请求时,没有了接受操作,呵呵
所以把监听函数改成:
private void Listen()
{
TcpListener listener = new TcpListener(Int32.Parse(txtClientPort.Text));
listener.Start();//<<<<---
while(true)
{
socket = listener.AcceptSocket();//<<<<---
string strTxt = string.Empty;
strTxt = CommunicationBase.ReadTextFromSocket(socket);//该方法是从socket中读取文本
lbReceiveMessage.Items.Add( strTxt);
}
}
即可!
或者在客户端保持一个“全局”的socket连接,设个按钮“连接服务器”,以后一直用这个socket!
understand???^_^