客户端主要源代码:
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();
}
}