class sendstream
{
public void duoxiancheng()
{ IPAddress adr = IPAddress.Parse("127.0.0.1");
TcpListener listener = new TcpListener(adr, 8000);
listener.Start();
Thread mythread = new Thread(new ParameterizedThreadStart(jianting));
mythread.Start(listener);
}
private void jianting(object Listener)
{
TcpClient newclient;
TcpListener listener = (TcpListener)Listener; while(true)
{
try
{
const int BufferSize = 8192;
newclient = listener.AcceptTcpClient();
NetworkStream streamToClient = newclient.GetStream();
byte[] buffer = new byte[BufferSize];
int bytesRead = streamToClient.Read(buffer, 0, BufferSize);
string msg = Encoding.Unicode.GetString(buffer, 0, bytesRead);
MessageBox.Show(msg);
} catch
{
break;
} }
}
}
代码有点多 希望能耐心看
问题 建立好通信后 利用线程 传送数据
但是这里的 msg 不能当做返回值 返回出来
我想将msg的内容 写在 Textbox上
高手如何实现
{
public void duoxiancheng()
{ IPAddress adr = IPAddress.Parse("127.0.0.1");
TcpListener listener = new TcpListener(adr, 8000);
listener.Start();
Thread mythread = new Thread(new ParameterizedThreadStart(jianting));
mythread.Start(listener);
}
private void jianting(object Listener)
{
TcpClient newclient;
TcpListener listener = (TcpListener)Listener; while(true)
{
try
{
const int BufferSize = 8192;
newclient = listener.AcceptTcpClient();
NetworkStream streamToClient = newclient.GetStream();
byte[] buffer = new byte[BufferSize];
int bytesRead = streamToClient.Read(buffer, 0, BufferSize);
string msg = Encoding.Unicode.GetString(buffer, 0, bytesRead);
MessageBox.Show(msg);
} catch
{
break;
} }
}
}
代码有点多 希望能耐心看
问题 建立好通信后 利用线程 传送数据
但是这里的 msg 不能当做返回值 返回出来
我想将msg的内容 写在 Textbox上
高手如何实现
然后在方法jianting()内赋值,再新建一个线程不断的监视这个msg,就可以了。
把这句换成textbox.text = msg应该可以吧。不可以的话用委托赋值。印象里直接赋值是可以的
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.Threading;
namespace ThreadText
{
delegate void SetTextCallback(string text);
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private Thread demoThread = null;
private void Form1_Load(object sender, EventArgs e)
{
this.demoThread =
new Thread(new ThreadStart(this.ThreadProcUnsafe)); this.demoThread.Start(); }
// This method is executed on the worker thread and makes
// an unsafe call on the TextBox control.
private void ThreadProcUnsafe()
{
this.SetText("This text was set safely."); }
private void SetText(string text)
{
// InvokeRequired required compares the thread ID of the
// calling thread to the thread ID of the creating thread.
// If these threads are different, it returns true.
if (this.textBox1.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
this.Invoke(d, new object[] { text });
}
else
{
this.textBox1.Text = text;
}
} }
}
这个名字应该改成ThreadProcSafe()
现在要将 MSG 传递到另一个类中
textbox不在同一个类中
初步思路是利用这个类得到MSG 然后作为返回值 在另个类中使用该MSG 现在在这个通信类中 总是提示
并非所有的代码路径都返回值
没有返回值 我没法在另个有TEXTBOX 的类中调用该 MSG 没有返回值 不知道如何实现
检测你的函数
检查每个分支
一定是有一个分支没有return