多线程
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Threading;
using System.Net.Sockets;
using System.Windows.Forms;
namespace WinTcpServer1
{
public partial class Form1 : Form
{
private TcpClient clent;
private NetworkStream ns;
public Form1()
{
InitializeComponent();
}
private void SendMsg()
{
IPAddress ip = IPAddress.Parse("127.0.0.1");
TcpListener lis = new TcpListener(ip, 777);
lis.Start();
clent = lis.AcceptTcpClient();
ns = clent.GetStream();
byte[] outbytes = Encoding.GetEncoding("gb2312").GetBytes(richTextBox2.Text.Trim());
ns.Write(outbytes, 0, outbytes.Length);
ns.Close();
clent.Close();
lis.Stop();
}
private void ReceviMsg()
{
byte[] inbytes = new byte[1024];
clent = new TcpClient("127.0.0.1", 777);
ns = clent.GetStream();
ns.Read(inbytes, 0, inbytes.Length);
richTextBox1.Text = Encoding.GetEncoding("gb2312").GetString(inbytes);
ns.Close();
clent.Close();
}
private void SendMsg_Click(object sender, EventArgs e)
{
Thread thd = new Thread(new ThreadStart(SendMsg));
thd.Priority = ThreadPriority.Normal;
thd.Start();
}
private void RecviMsg_Click(object sender, EventArgs e)
{
try
{
Thread tha = new Thread(new ThreadStart(ReceviMsg));
tha.Priority = ThreadPriority.Normal;
tha.Start();
}
catch (Exception ep)
{
MessageBox.Show(ep.Message);
}
}
}
}