简单的网络连接1
--客户端
public FChatClient()
{
InitializeComponet()
}
private void btnConnect_Click(object sender,EventArgs e)
{
IPAddress address = IPAddress.Parse(txtIP.Text.Trim());
IPEndPoint endpoint = new IPEndPiont(address,int.Parse(txtPort.Text.Trim());
Socket socketWatch = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
socketWatch.Connect(endpoint);
}
--服务端
public FChatServer()
{
InitializeComponet()
TextBox.CheckForIllegalCrossThreadCalls = false;
}
Thread threadWatch = null;
Socket socWatch = null;
public void btnBeginListen_Click(object sender,EventArgs e)
{
socWatch = new Scoket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
IPAddress address = IPAddress.Parse(txtIP.Text.Trim());
IPEndPoint endpoint = new IPEndPoint(address,int.Parse(txtPort.Text.Trim());
socketWatch.Bind(endpoint);
socketWatch.Listen(10);
threadWatch = new Thread(WatchConnection);
threadWatch.IsBackground = true;
threadWatch.Start();
ShowMsg("服务器启动监听成功");
}
void WatchConnection()
{
Socket socConnection = socWatch.Accept();//一旦监听到客户端的请求,就返回一个负责和该客户通信的套接字
ShowMsg("客户端连接成功!");
}
void ShowMsg(string msg)
{
txtMessage.AppendText(msg + "\r\n")
}
posted on 2013-12-08 11:10 Efforts to achieve 阅读(177) 评论(0) 编辑 收藏 举报