日期:2014-05-18 浏览次数:21059 次
Socket server; Socket client; Thread s; IPAddress ip = IPAddress.Parse("127.0.0.1"); int prot = 6000; /// <summary> /// 开始监听 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button1_Click(object sender, EventArgs e) { //输入IP try { ip = IPAddress.Parse(textBox1.Text); } catch { textBox3.Text = "你输入的IP地址格式不正确,请重新输入!"; } //输入端口 try { int i = Int32.Parse(textBox2.Text); if (i >= 0 && i <= 65535) { prot = i; } else { textBox3.Text = "请输入0--65535之间的数字"; } } catch { textBox3.Text = "请输入端口号!"; } //开始监听 try { s = new Thread(new ThreadStart(start)); s.Start(); } catch (Exception ee) { textBox3.Text = ee.Message; } } /// <summary> /// 监听请求 /// </summary> void start() { //创建套接字 server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //绑定到本地 IPEndPoint ipPoint = new IPEndPoint(ip, prot); server.Bind(ipPoint); //开始侦听 server.Listen(5); //接受客户端请求 client = server.Accept(); textBox3.Text = "主机" + Dns.GetHostName() + "端口" + textBox2.Text + "开始监听........"; if (client.Connected) { textBox3.Text = "与客户端建立了连接"; while (true) { //接受数据 byte[] data = new byte[1024]; int size = client.Receive(data); string result = Encoding.Unicode.GetString(data, 0, size); if (result == "[---===退出===---]") { textBox3.Text = "你失去了与客户端的联系"; server.Shutdown(SocketShutdown.Both); server.Close(); } //richTextBox1.AppendText(result); else { string[] aa = result.Split('~'); richTextBox1.AppendText(aa[0] + "说:" + aa[1] + "\r"); } } } } private void button4_Click(object sender, EventArgs e) { try { //发送数据 //byte[] msg = Encoding.Unicode.GetBytes(richTextBox2.Text); byte[] msg = Encoding.Unicode.GetBytes(Dns.GetHostName() + "~" + richTextBox2.Text); client.Send(msg); //这里既可以将BYTE类型的数组从新解码再输出也可以直接输出richTextBox2中的文本 string aa = Encoding.Unicode.GetString(msg); //richTextBox1.AppendText("本机&q