代码如下:
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.Threading;
namespace TcpServers
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private Thread thread;
private TcpListener listener;
private TcpClient client;
private static string massege="";
private void ShowMassege() //在接收消息窗口显示消息
{
while (massege != "")
{
try
{
rtbread.AppendText(massege);
rtbread.ScrollToCaret();
massege = "";
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
private void StartListen() //开始监听
{
//获取IP地址
string hostname = Dns.GetHostName();
IPAddress[] IP = Dns.GetHostAddresses(hostname);
// MessageBox.Show(IP[4].ToString());
listener=new TcpListener(IP[4] ,8000) ;
listener.Start();
while (true ) //获取消息
{
client = listener.AcceptTcpClient();
NetworkStream netstm = client.GetStream();
byte[] mybyte = new byte[1024];
int length = netstm.Read(mybyte, 0, mybyte.Length);
massege = Encoding.Default.GetString(mybyte, 0, length);
}
}
private void Form1_Load(object sender, EventArgs e)
{
//显示本机IP
IPAddress[] IP = Dns.GetHostAddresses(Dns.GetHostName());
this.labelIP.Text = IP[4].ToString();
thread = new Thread(new ThreadStart(this.StartListen));
thread.Start();
timer1.Start();
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
if (this.listener != null) //判断侦听对象是否关闭
{
listener.Stop(); //停止侦听
}
if (thread != null) //判断线程是否为空
{
if (thread.ThreadState == ThreadState.Running) //判断线程是否正在运行
{
thread.Abort(); //终止线程
}
}
}
private void timer1_Tick(object sender, EventArgs e)
{
ShowMassege();
}
}
}
我是用Encoding接收消息啊。
你说的那两个Encoder,Decoder怎么接收消息啊?