C#Socket 案例
服务器端
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; using System.IO; namespace wangluoqi { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { //点击监听按钮时 创建Socket对像 Socket socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创建一个Socket对象,如果用UDP协议,则要用SocketTyype.Dgram类型的套接字 //声明ip地址 IPAddress ip = IPAddress.Any; //创建端口对像 IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32(txtprot.Text)); //开始监听 socketWatch.Bind(point); ShowMsg("监听成功"); //声明一秒内可同时连接的客户端 socketWatch.Listen(10); //创建后台进程用来监听连接 Thread td = new Thread(listen); td.IsBackground = true; td.Start(socketWatch); } Socket socketSend; Dictionary<string, Socket> dc = new Dictionary<string, Socket>(); /// <summary> /// 创建通信的客户端 /// </summary> /// <param name="o"></param> void listen(object o) { //把对像转成socket 如果不为socket 返回null Socket socketwatch = o as Socket; while (true) { //等待客户端连接 创建一个负责通信的Socket socketSend = socketwatch.Accept(); dc.Add(socketSend.RemoteEndPoint.ToString(), socketSend); comboBox1.Items.Add(socketSend.RemoteEndPoint.ToString()); ShowMsg(socketSend.RemoteEndPoint.ToString() + ":连接成功"); //新建一个进程,以免程序假死 Thread th = new Thread(Receive); th.IsBackground = true; th.Start(socketSend); } } /// <summary> /// 不停的接收传过来的数据 /// </summary> /// <param name="o"></param> void Receive(object o) { try { while (true) { Socket socketSend = o as Socket; byte[] buffer = new byte[1024 * 1024 * 2]; int r = socketSend.Receive(buffer); if (r == 0) { break; } string str = Encoding.UTF8.GetString(buffer, 0, r); ShowMsg(socketSend.RemoteEndPoint + ":" + str); } } catch { } } private void ShowMsg(string str) { txtlog.AppendText(str + "\r\n"); } private void Form1_Load(object sender, EventArgs e) { //取消跨线层访问判断 Control.CheckForIllegalCrossThreadCalls = false; } private void button4_Click(object sender, EventArgs e) { string str = txtsend.Text; byte[] buf = Encoding.UTF8.GetBytes(str); List<byte> blist = new List<byte>(); blist.Add(0); blist.AddRange(buf); //将泛型集合转为数组 byte[] nbuf = blist.ToArray(); if (comboBox1.SelectedItem == null) { comboBox1.SelectedIndex = 0; } dc[comboBox1.SelectedItem.ToString()].Send(nbuf); // socketSend.Send(buf); } private void button2_Click(object sender, EventArgs e) { OpenFileDialog odg = new OpenFileDialog(); odg.InitialDirectory = @"C:\Users\Administrator\Desktop"; odg.ShowDialog(); string filepath = odg.FileName; txtfilename.Text = filepath; } //发送文本 private void button3_Click(object sender, EventArgs e) { string stpath = txtfilename.Text; if (comboBox1.SelectedItem == null) { comboBox1.SelectedIndex = 0; } using(FileStream fsRead=new FileStream(stpath,FileMode.OpenOrCreate,FileAccess.Read)) { byte[] buf = new byte[1024 * 1024 * 5]; int r = fsRead.Read(buf, 0, buf.Length); List<byte> nlist= new List<byte>(); nlist.Add(1); nlist.AddRange(buf); //将集合转为数组; byte[] nbuf = nlist.ToArray(); dc[comboBox1.SelectedItem.ToString()].Send(nbuf, 0, r+1, SocketFlags.None); } } //发送窗口抖动 private void button5_Click(object sender, EventArgs e) { if (comboBox1.SelectedItem == null) { comboBox1.SelectedIndex = 0; } byte[] buf = new byte[1]; buf[0] = 2; dc[comboBox1.SelectedItem.ToString()].Send(buf); } } }
客户端
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; namespace clent { public partial class Form1 : Form { public Form1() { InitializeComponent(); } Socket socketsend = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //连接服务器 private void button1_Click(object sender, EventArgs e) { //创建连接用的socket //创建连接点 IPAddress ip = IPAddress.Parse(txtip.Text); //创建要连接的网络点 IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32(txtpint.Text)); //连接 socketsend.Connect(point); ShowMsg("连接成功"); //创建一个后台线层,用于接收服务器发来的数据 Thread td = new Thread(jssend); td.IsBackground = true; td.Start(); } /// <summary> /// 接收数据 /// </summary> void jssend() { try { while (true) { byte[] buf = new byte[1024 * 1024 * 2]; //实际接收到的字符数 int r = socketsend.Receive(buf); if (r == 0) { break; } //表示接收到的数据是文本 if (buf[0] == 0) { string str = Encoding.UTF8.GetString(buf, 1, r-1); txtlog.AppendText(socketsend.RemoteEndPoint + ":" + str + "\r\n"); } else if (buf[0] == 1)//表示接收到的数据是文件 { SaveFileDialog sdg = new SaveFileDialog(); sdg.InitialDirectory = @"C:\Users\Administrator\Desktop"; sdg.Title = "选择保存位置"; sdg.ShowDialog(this);//此处一定要添加this string filename = sdg.FileName; using (FileStream fsw = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.ReadWrite)) { fsw.Write(buf, 1, r - 1); } MessageBox.Show("保存成功"); } else if (buf[0] == 2)//表示接收到的数据是窗口抖动 { int x = this.Location.X; int y = this.Location.Y; for (int i = 0; i < 100; i++) { this.Location = new Point(x - 10, y - 10); this.Location = new Point(x, y); } } } } catch{} } void ShowMsg(string str) { txtlog.AppendText(str + "\r\n"); } private void button2_Click(object sender, EventArgs e) { byte[] buf = Encoding.UTF8.GetBytes(txtsend.Text); socketsend.Send(buf); } private void Form1_Load(object sender, EventArgs e) { Control.CheckForIllegalCrossThreadCalls = false; } } }