C#缃戠粶缂栫▼锛屽叧浜庣洃鍚?涓轰粈涔堝湪鐩戝惉鐨勬椂鍊欐姤閿?- 宸茶В鍐?- 鎼滄悳闂棶
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Net.Sockets;
using System.Net;
using System.Threading;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
int port = 8000;
private Thread thRead;
private TcpListener tcpl;
private bool bListener = true;
private Socket stRead;
public Form1()
{
InitializeComponent();
}
private void Listen()
{
try
{
tcpl = new TcpListener(IPAddress.Parse("127.0.0.1"),port);
tcpl.Start();
statusBar1.Text = "姝e湪鐩戝惉";
stRead = tcpl.AcceptSocket();
EndPoint epTemp = stRead.RemoteEndPoint;
IPEndPoint ipe = (IPEndPoint)epTemp;
IPHostEntry host = Dns.GetHostEntry(ipe.Address);
string name = host.HostName;
statusBar1.Text = "宸茬粡杩炰笂";
while (bListener)
{
string sTime = DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToLongTimeString();
listBox1.Items.Add(sTime);
byte[] buf = new byte[80];
int iRead = stRead.ReceiveFrom(buf, ref epTemp);
byte[] bText = new byte[iRead];
Array.Copy(buf, 0, bText, 0,iRead);
string sTemp = Encoding.Default.GetString(bText);
if (sTemp.Trim() == "Stop")
{
stRead.Shutdown(SocketShutdown.Both);
stRead.Close();
tcpl.Stop();
statusBar1.Text = "杩炴帴宸茬粡鍏抽棴";
thRead.Abort();
button1.Enabled = true;
return;
}
else
listBox1.Items.Add(sTemp);
}
}
catch
{
MessageBox.Show("渚﹀惉澶辫触");
button1.Enabled = true;
}
}
private void button1_Click(object sender, EventArgs e)
{
thRead = new Thread(new ThreadStart(Listen));
thRead.Start();
button1.Enabled = false;
}
}
}
銆?*******************************************************************************************