tlTcpListen.Start ( ) ; //开始监听
statusBar1.Text = "正在监听" ;
tcClient = tlTcpListen.AcceptTcpClient ( ) ; //通过TCP连接请求
nsStream = tcClient.GetStream ( ) ; //获取用以发送、接收数据的网络基础数据流
srRead=new StreamReader(nsStream);//以得到的网络基础数据流来初始化StreamReader实例
statusBar1.Text = "已经连接!";
while( blistener ) //循环侦听
{
string sMessage = srRead.ReadLine();//从网络基础数据流中读取一行数据
if ( sMessage == "STOP" ) //判断是否为断开TCP连接控制码
{
tlTcpListen.Stop(); //关闭侦听
nsStream.Close(); //释放资源
srRead.Close();
statusBar1.Text = "连接已经关闭!" ;
thThreadRead.Abort(); //中止线程
return;
}
string sTime = DateTime.Now.ToShortTimeString ( ) ; //获取接收数据时的时间
listBox1.Items.Add ( sTime + " " + sMessage ) ;
}
}
catch ( System.Security.SecurityException )
{
MessageBox.Show ( "侦听失败!" , "错误" ) ;
}
}
//开始监听
private void button1_Click(object sender, System.EventArgs e)
{
thThreadRead = new Thread ( new ThreadStart ( Listen ) );
thThreadRead.Start();//启动线程
button1.Enabled=false;
}
// 清理所有正在使用的资源。
protected override void Dispose( bool disposing )
{
try
{
tlTcpListen.Stop(); //关闭侦听
nsStream.Close();
srRead.Close();//释放资源
thThreadRead.Abort();//中止线程
}
catch{}
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
TCP协议的发送端
using System.Net.Sockets; //使用到TcpListen类
using System.Threading; //使用到线程
using System.IO; //使用到StreamWriter类
using System.Net; //使用IPAddress类、IPHostEntry类等
private StreamWriter swWriter; //用以向网络基础数据流传送数据
private NetworkStream nsStream; //创建发送数据的网络基础数据流
private TcpClient tcpClient;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.TextBox textBox1;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.TextBox textBox2;
private System.Windows.Forms.StatusBar statusBar1;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2; //通过它实现向远程主机提出TCP连接申请
private bool tcpConnect = false; //定义标识符,用以表示TCP连接是否建立
//连接
private void button1_Click(object sender, System.EventArgs e)
{
IPAddress ipRemote ;
try
{
ipRemote = IPAddress.Parse ( textBox1.Text ) ;
}
catch //判断给定的IP地址的合法性
{
MessageBox.Show ( "输入的IP地址不合法!" , "错误提示!" ) ;
return ;
}
IPHostEntry ipHost ;
try
{
ipHost = Dns.Resolve ( textBox1.Text ) ;
}
catch //判断IP地址对应主机是否在线
{
MessageBox.Show ("远程主机不在线!" , "错误提示!" ) ;
return ;
}
string sHostName = ipHost.HostName ;
try
{
TcpClient tcpClient = new TcpClient(sHostName,8000);//对远程主机的8000端口提出TCP连接申请
nsStream = tcpClient.GetStream();//通过申请,并获取传送数据的网络基础数据