int port = 8000 ;
//定义侦听端口号
private TcpClient tcpc ;
//对服务器端创建TCP连接
private Socket stSend ;
//创建发送数据套接字
private bool tcpConnect = false ;
//定义标识符,用以表示TCP连接是否建立
//定义侦听端口号
private TcpClient tcpc ;
//对服务器端创建TCP连接
private Socket stSend ;
//创建发送数据套接字
private bool tcpConnect = false ;
//定义标识符,用以表示TCP连接是否建立
private void button1_Click
( object sender , System.EventArgs e )
{
//以下代码是判断是否和远程终结点成功连接
try
{
stSend = new Socket ( AddressFamily.InterNetwork ,
SocketType.Stream , ProtocolType.Tcp ) ;
//初始化一个Socket实例
IPEndPoint tempRemoteIP = new IPEndPoint
( IPAddress.Parse ( textBox1.Text ) , port ) ;
//根据IP地址和端口号创建远程终结点
EndPoint epTemp = ( EndPoint ) tempRemoteIP ;
stSend.Connect ( epTemp ) ;
//连接远程主机的8000端口号
statusBar1.Text = "成功连接远程计算机!" ;
tcpConnect = true ;
button1.Enabled = false ;
button2.Enabled = true ;
}
catch ( Exception )
{
statusBar1.Text = "目标计算机拒绝连接请求!" ;
}
}
( object sender , System.EventArgs e )
{
//以下代码是判断是否和远程终结点成功连接
try
{
stSend = new Socket ( AddressFamily.InterNetwork ,
SocketType.Stream , ProtocolType.Tcp ) ;
//初始化一个Socket实例
IPEndPoint tempRemoteIP = new IPEndPoint
( IPAddress.Parse ( textBox1.Text ) , port ) ;
//根据IP地址和端口号创建远程终结点
EndPoint epTemp = ( EndPoint ) tempRemoteIP ;
stSend.Connect ( epTemp ) ;
//连接远程主机的8000端口号
statusBar1.Text = "成功连接远程计算机!" ;
tcpConnect = true ;
button1.Enabled = false ;
button2.Enabled = true ;
}
catch ( Exception )
{
statusBar1.Text = "目标计算机拒绝连接请求!" ;
}
}
private void button2_Click
( object sender , System.EventArgs e )
{
int iLength = textBox2.Text.Length ;
//获取要发送的数据的长度
Byte [ ] bySend = new byte [ iLength ] ;
//根据获取的长度定义一个Byte类型数组
bySend = System.Text.Encoding.Default.GetBytes
( textBox2.Text ) ;
//按照指定编码类型把字符串指定到指定的Byte数组
int i = stSend.Send ( bySend ) ;
//发送数据
listBox1.Items.Add ( textBox2.Text ) ;
}
( object sender , System.EventArgs e )
{
int iLength = textBox2.Text.Length ;
//获取要发送的数据的长度
Byte [ ] bySend = new byte [ iLength ] ;
//根据获取的长度定义一个Byte类型数组
bySend = System.Text.Encoding.Default.GetBytes
( textBox2.Text ) ;
//按照指定编码类型把字符串指定到指定的Byte数组
int i = stSend.Send ( bySend ) ;
//发送数据
listBox1.Items.Add ( textBox2.Text ) ;
}
protected override void Dispose ( bool disposing )
{
if ( tcpConnect )
{
Byte [ ] bySend = new byte [ 4 ] ;
//根据字符串“STOP”长度来定义Byte数组
bySend = System.Text.Encoding.
Default.GetBytes ( "STOP" ) ;
int i = stSend.Send ( bySend ) ;
//发送控制码
stSend.Close ( ) ;
//关闭套接字
}
if ( disposing )
{
if ( components != null )
{
components.Dispose ( ) ;
}
}
base.Dispose ( disposing ) ;
}
{
if ( tcpConnect )
{
Byte [ ] bySend = new byte [ 4 ] ;
//根据字符串“STOP”长度来定义Byte数组
bySend = System.Text.Encoding.
Default.GetBytes ( "STOP" ) ;
int i = stSend.Send ( bySend ) ;
//发送控制码
stSend.Close ( ) ;
//关闭套接字
}
if ( disposing )
{
if ( components != null )
{
components.Dispose ( ) ;
}
}
base.Dispose ( disposing ) ;
}