首页 > 代码库 > winform socket编程之TCPListener
winform socket编程之TCPListener
运行结果:
服务端代码
1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel; 4 using System.Data; 5 using System.Drawing; 6 using System.Linq; 7 using System.Net; 8 using System.Net.Sockets; 9 using System.Text; 10 using System.Threading; 11 using System.Threading.Tasks; 12 using System.Windows.Forms; 13 14 namespace SocketServer 15 { 16 public partial class Form1 : Form 17 { 18 private List<TcpClient> clientList=new List<TcpClient>();///保存客户连接socket 19 private TcpListener tcpListener;///监听类 20 21 public Form1() 22 { 23 InitializeComponent(); 24 } 25 26 private void button3_Click(object sender, EventArgs e) 27 { 28 tcpListener = new TcpListener(IPAddress.Any, 3000);//监听3000端口 29 tcpListener.Start();//开始监听 30 Thread listenThread = new Thread(new ThreadStart(ListenForClients));///新建线程来处理新的客户端连接 31 listenThread.Start(); 32 33 } 34 35 /// <summary> 36 /// 处理客户端连接线程 37 /// </summary> 38 private void ListenForClients() 39 { 40 while (true) 41 { 42 //blocks until a client has connected to the server 43 TcpClient client = this.tcpListener.AcceptTcpClient(); 44 clientList.Add(client); 45 listBox2.BeginInvoke(new Action(()=>{listBox2.Items.Add(client.Client.RemoteEndPoint.ToString());})); 46 //create a thread to handle communication 47 //with connected client 48 Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm)); 49 clientThread.Start(client); 50 51 } 52 } 53 54 /// <summary> 55 /// 读客户端数据 56 /// </summary> 57 /// <param name="client"></param> 58 private void HandleClientComm(object client) 59 { 60 TcpClient tcpClient = (TcpClient)client; 61 NetworkStream clientStream = tcpClient.GetStream(); 62 byte[] message = new byte[4096]; 63 int bytesRead; 64 while (true) 65 { 66 bytesRead = 0; 67 try 68 { 69 //blocks until a client sends a message,每个线程在这一句时会中断一下,等待客户端有数据传进来后再往下执行 70 bytesRead = clientStream.Read(message, 0, 4096); 71 } 72 catch 73 { 74 //a socket error has occured 75 break; 76 } 77 if (bytesRead == 0) 78 { 79 //the client has disconnected from the server 80 break; 81 } 82 83 //message has successfully been received 84 UTF8Encoding utf8 = new UTF8Encoding(); 85 System.Diagnostics.Debug.WriteLine(utf8.GetString(message, 0, bytesRead)); 86 ///线程里修改UI界面的内容要用invoke方法和委托 87 listBox1.Invoke(new Action(() => { listBox1.Items.Add(utf8.GetString(message, 0, bytesRead)); })); 88 } 89 90 //tcpClient.Close();//不要关闭 91 } 92 93 /// <summary> 94 /// 向所有客户端发送 95 /// </summary> 96 /// <param name="sender"></param> 97 /// <param name="e"></param> 98 private void button4_Click(object sender, EventArgs e) 99 { 100 foreach (var item in clientList) 101 { 102 NetworkStream stream=item.GetStream(); 103 stream.Write(UTF8Encoding.UTF8.GetBytes(this.textBox1.Text), 0, UTF8Encoding.UTF8.GetBytes(this.textBox1.Text).Length); 104 } 105 } 106 } 107 }
客户端代码
1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel; 4 using System.Data; 5 using System.Drawing; 6 using System.Linq; 7 using System.Net; 8 using System.Net.Sockets; 9 using System.Text; 10 using System.Threading; 11 using System.Threading.Tasks; 12 using System.Windows.Forms; 13 14 namespace EdoecSpeaker 15 { 16 public partial class Form1 : Form 17 { 18 TcpClient client; 19 public Form1() 20 { 21 InitializeComponent(); 22 } 23 24 /// <summary> 25 /// 连接服务器 26 /// </summary> 27 /// <param name="sender"></param> 28 /// <param name="e"></param> 29 private void button3_Click(object sender, EventArgs e) 30 { 31 if (client==null) 32 { 33 client = new TcpClient(); 34 IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 3000); 35 client.Connect(serverEndPoint); 36 Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm)); 37 clientThread.Start(client); 38 } 39 //clientStream.Flush(); 40 } 41 42 /// <summary> 43 /// 接收消息 44 /// </summary> 45 /// <param name="client"></param> 46 private void HandleClientComm(object client) 47 { 48 TcpClient tcpClient = (TcpClient)client; 49 NetworkStream clientStream = tcpClient.GetStream(); 50 51 byte[] message = new byte[4096]; 52 int bytesRead; 53 54 while (true) 55 { 56 bytesRead = 0; 57 58 try 59 { 60 //blocks until a client sends a message 61 bytesRead = clientStream.Read(message, 0, 4096); 62 } 63 catch 64 { 65 //a socket error has occured 66 break; 67 } 68 69 if (bytesRead == 0) 70 { 71 //the client has disconnected from the server 72 break; 73 } 74 75 //message has successfully been received 76 UTF8Encoding utf8 = new UTF8Encoding(); 77 System.Diagnostics.Debug.WriteLine(utf8.GetString(message, 0, bytesRead)); 78 listBox1.Invoke(new Action(() => { listBox1.Items.Add(utf8.GetString(message, 0, bytesRead)); })); 79 } 80 //tcpClient.Close(); 81 } 82 83 /// <summary> 84 /// 发送消息 85 /// </summary> 86 /// <param name="sender"></param> 87 /// <param name="e"></param> 88 private void button4_Click(object sender, EventArgs e) 89 { 90 NetworkStream clientStream = client.GetStream(); 91 clientStream.Write(UTF8Encoding.UTF8.GetBytes(this.textBox1.Text), 0, UTF8Encoding.UTF8.GetBytes(this.textBox1.Text).Length); 92 } 93 } 94 }
winform socket编程之TCPListener
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。