标签:
实现了,局域网客户端 对客户端 的通讯。 实际上这是 一个 客户端 兼 服务端 。
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO; using System.Net; using System.Net.Sockets; using System.Threading; namespace 模拟客服端01 { public partial class Form1 : Form { public Form1() { InitializeComponent(); TextBox.CheckForIllegalCrossThreadCalls = false;//禁止多线程检查 } Socket socket_My; // 主动建立连接套接字 Socket socket_Listen; // 监听套接字 Socket socket_Accept; // 接收套接字 Thread thread_Receive;//接收 线程 Thread thread_Accept; // 发送线程 public void Accept() { while (true) { socket_Accept = socket_Listen.Accept(); // 监听套接字 接收 请求 返回 接收套接字 textBoxMag.AppendText("客户端连接成功!" + socket_Accept.RemoteEndPoint + "\r\n"); thread_Accept = new Thread(Receive); thread_Accept.IsBackground = true; thread_Accept.Start(); } } public void Receive() { while (true) { try { byte[] B = new byte[1024]; socket_Accept.Receive(B);// 接收套接字 接收信息 string Message = Encoding.UTF8.GetString(B, 0, B.Length); if (!string.IsNullOrEmpty(Message)) { textBoxMag.AppendText(Message + "\r\n"); } } catch (Exception) { textBoxMag.AppendText("连接关闭了" + "\r\n"); btn_Conncet.Enabled = false; break; } } } private void StartListen_Click(object sender, EventArgs e) { socket_Listen = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket_Listen.Bind(new IPEndPoint(IPAddress.Any, int.Parse(textBoxMyPort.Text))); socket_Listen.Listen(10); textBoxMag.AppendText("开始监听" + "\r\n"); thread_Receive = new Thread(Accept); thread_Receive.IsBackground = true; thread_Receive.Start(); StartListen.Enabled = false; } private void btn_Conncet_Click(object sender, EventArgs e) { try { socket_My = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket_My.Connect(new IPEndPoint(IPAddress.Parse(textBoxIP.Text), int.Parse(textBoxPort.Text))); btn_Conncet.Enabled = false; } catch (Exception ex) { textBoxMag.AppendText("连接不上" + "\r\n"); } } private void button_Send_Click(object sender, EventArgs e) { try { socket_My.Send(Encoding.UTF8.GetBytes(textBoxSend.Text + "\r\n")); } catch (Exception) { textBoxMag.AppendText("发送失败" + "\r\n"); } } } }
这里指明了 端口号,和IP ,接下来 ,做一个服务端 记录 它说有客户端的 IP 的通讯端口就好了。
标签:
原文地址:http://www.cnblogs.com/bingguang/p/4558587.html