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 ) ;
}