客戶端
using System.Windows.Forms;
using System.Net.Sockets;
using System.Threading;
using System.IO;
using System.Net;//使用IPAredd類,IPHostEntry類
namespace QQ
{
public partial class Tcpclient : Form
{
private StreamWriter write;
private NetworkStream stream;
private TcpClient tcpclient;
public Tcpclient()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
tcpclient = new TcpClient(AddressFamily.InterNetwork);
tcpclient.Connect("127.0.0.1",8000);
stream = tcpclient.GetStream();
write = new StreamWriter(stream);
write.WriteLine(this.textBox1.Text);
write.Flush();
}
catch
{
}
}
}
}
服務器端
using System.Net.Sockets;//使用了TcpListen類
using System.Threading;//使用到了線程
using System.IO;//使用到了StreamReader類
using System.Net;
namespace QQ
{
public partial class Tcpserver : Form
{
int port = 8000;//定義偵聽端口號
private Thread threadRead; //創建線程,用以偵聽端口號,接受信息
private TcpListener tcpListen;//偵聽端口號
private bool blistener = true;
private NetworkStream stream;
private StreamReader read;
private TcpClient client;
private delegate void listbox_show(string str);
listbox_show listboxshow;
public Tcpserver()
{
InitializeComponent();
listboxshow = new listbox_show(show);
}
private void Listen()
{
try
{
tcpListen = new TcpListener(8000); //用8000端口來初始化TcpListener實例
tcpListen.Start();//開始監聽
client = tcpListen.AcceptTcpClient();//通過tcp連接請求
stream = client.GetStream(); //獲取基本的流
read = new StreamReader(stream); //用得到的網絡基礎數據流來初始化StreamReader實例
while (blistener)
{
string message = read.ReadLine();//從網絡基礎數據流中讀取一行數據
if (message == "STOP")
{
tcpListen.Stop();//關閉偵聽
stream.Close();//釋放資源
read.Close();
threadRead.Abort();
return;
}
string sTime = DateTime.Now.ToShortDateString();
listBox1.Invoke(listboxshow,sTime + " " + message);
}
}
catch (System.Security.SecurityException)
{
MessageBox.Show("偵聽失敗!","錯誤");
}
}
private void show(string str)
{
this.listBox1.Items.Add(str);
}
//開始偵聽
private void button1_Click(object sender, EventArgs e)
{
threadRead = new Thread(new ThreadStart(Listen));
threadRead.Start();
this.button1.Enabled = false;
}
}
}