Socket 编程
Socket通信基本流程
由此建立一个server和client相互通信的代码分别为:
Server相关:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Net.Sockets; using System.Net; using System.Threading; namespace Scoket编程 { public partial class Form_Server : Form { public Form_Server() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { } private void button2_Click(object sender, EventArgs e) { //当点击开始监听的时候 在服务器创建一个负责监视IP地址跟端口号的Socket //使用ipv4地址,流式Socket方式,tcp传输协议 Socket socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream,ProtocolType.Tcp); //设置IP地址 IPAddress ip = IPAddress.Parse(txtIP.Text); //IPAddress ip = IPAddress.Any; //创建端口对象 IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32(txtPort.Text)); try { //将socket绑定到特定的地址 socketWatch.Bind(point); //监听 //同一个时间点过来10个客户端,排队 socketWatch.Listen(10); ShowMsg("服务器开始监听"); Thread th = new Thread(AccpetInfo); th.IsBackground = true; th.Start(socketWatch); } catch(Exception ex) { MessageBox.Show(ex.Message); } } //记录通信用的socket Dictionary<string, Socket> dic = new Dictionary<string, Socket>(); void AccpetInfo(object o) { Socket socket = o as Socket; while(true) { try { //创建通信用的Socket Socket tsocket = socket.Accept(); string point = tsocket.RemoteEndPoint.ToString(); ShowMsg(point + "连接成功!"); cboIpPort.Items.Add(point); cboIpPort.SelectedIndex = cboIpPort.Items.Count - 1; dic.Add(point, tsocket); //接受消息 Thread th = new Thread(ReceiveMsg); th.IsBackground = true; th.Start(tsocket); } catch(Exception ex) { MessageBox.Show(ex.Message); break; } } } //接收消息 void ReceiveMsg(object o) { Socket client = o as Socket; try { while (true) { //接收客户端发来的消息 byte[] buffer = new byte[1024 * 1024]; //将接收来的数据放到buffer中,并返回实际接收到的数据长度 int n = client.Receive(buffer); //如果接收的数据长度是0,表明已经远程连接已经断开,则跳出循环 if(n == 0) { break; } //将字节转成字符串 string words = Encoding.UTF8.GetString(buffer, 0, n); ShowMsg(client.RemoteEndPoint.ToString() + ":" + words); } } catch(Exception ex) { MessageBox.Show(ex.Message); } } void ShowMsg(string str) { txtLog.AppendText(str + "\r\n"); } private void Form1_Load(object sender, EventArgs e) { Control.CheckForIllegalCrossThreadCalls = false; } //给客户端发送消息 private void button5_Click(object sender, EventArgs e) { try { ShowMsg(txtSend.Text); string ip = cboIpPort.Text; byte[] buffer = Encoding.UTF8.GetBytes(txtSend.Text); dic[ip].Send(buffer); } catch(Exception ex) { ShowMsg(ex.Message); } } } }
Client相关:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Net.Sockets; using System.Net; using System.Threading; namespace Scoket编程 { public partial class Form_Client : Form { public Form_Client() { InitializeComponent(); } Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); private void btnConnect_Click(object sender, EventArgs e) { //连接到目标IP IPAddress ip = IPAddress.Parse(txtIp.Text); //连接到目标IP的端口号 IPEndPoint point = new IPEndPoint(ip, int.Parse(txtPort.Text)); try { //连接到服务器 client.Connect(point); ShowMsg("连接成功"); ShowMsg("服务器" + client.RemoteEndPoint.ToString()); ShowMsg("服务器" + client.LocalEndPoint.ToString()); //连接成功后,就可以接收服务器发送的消息了 Thread th = new Thread(ReceiveMsg); th.IsBackground = true; th.Start(); } catch(Exception ex) { MessageBox.Show(ex.Message); } } //接收服务器消息 void ReceiveMsg() { while(true) { try { byte[] buffer = new byte[1024 * 1024]; int n = client.Receive(buffer); string s = Encoding.UTF8.GetString(buffer, 0, n); ShowMsg(client.RemoteEndPoint.ToString() + ":" + s); } catch(Exception ex) { MessageBox.Show(ex.Message); } } } void ShowMsg(string str) { txtLog.AppendText(str + "\r\n"); } private void btnSend_Click(object sender, EventArgs e) { if(client != null) { try { ShowMsg(txtSend.Text); byte[] buffer = Encoding.UTF8.GetBytes(txtSend.Text); client.Send(buffer); } catch(Exception ex) { ShowMsg(ex.Message); } } } private void Form_Client_Load(object sender, EventArgs e) { Control.CheckForIllegalCrossThreadCalls = false; } private void txtSend_KeyPress(object sender, KeyPressEventArgs e) { //如果输入了回车,则执行发送; if(e.KeyChar == 13) { btnSend_Click(sender, e); } } } }