客戶端主要源代碼:
public void SendMeg()//發送信息
{
try
{
int port=Int32.Parse(textBox3.Text.ToString());//遠程主機端口
try
{
tcpClient=new TcpClient(textBox1.Text,port);//創建TcpClIEnt對象實例 }
catch(Exception le)
{
MessageBox.Show("TcpClIEnt Error:"+le.Message);
}
string strDateLine=DateTime.Now.ToShortDateString()+" "+DateTime.Now.ToLongTimeString();//得到發送時客戶端時間
netStream=tcpClIEnt.GetStream();//得到網絡流
sw=new StreamWriter(netStream);//創建TextWriter,向流中寫字符
string Words=textBox4.Text;//待發送的話
string content=strDateLine+Words;//待發送內容
sw.Write(content);//寫入流
sw.Close();//關閉流寫入器
netStream.Close();//關閉網絡流
tcpClIEnt.Close();//關閉客戶端連接
}
catch(Exception ex)
{
MessageBox.Show("Sending Message Failed!"+ex.Message);
}
textBox4.Text="";//清空
}
服務器端主要源代碼:
public void StartListen()//偵聽特定端口的用戶請求
{
//ReceiveMeg();
isLinked=false; //連接標志
try
{
int port=Int32.Parse(textBox1.Text.ToString());//本地待偵聽端口
serverListener=new TcpListener(port);//創建TcpListener對象實例
serverListener.Start(); //啟動偵聽
}
catch(Exception ex)
{
MessageBox.Show("Can‘t Start Server"+ex.Message);
return;
}
isLinked=true;
while(true)//進入無限循環等待用戶端連接
{
try
{
tcpClient=serverListener.AcceptTcpClIEnt();//創建客戶端連接對象
netStream=tcpClIEnt.GetStream();//得到網絡流
sr=new StreamReader(netStream);//流讀寫器
}
catch(Exception re)
{
MessageBox.Show(re.Message);
}
string buffer="";
string received="";
received+=sr.ReadLine();//讀流中一行
while(received.Length!=0)
{
buffer+=received;
buffer+="\r\n";
//received="";
received=sr.ReadLine();
}
listBox1.Items.Add(buffer);//顯示
//關閉
sr.Close();
netStream.Close();
tcpClIEnt.Close();
}
}