我是新手以前没写过博客 希望大家勿喷,
在编写Socket的时候需要导入System.Net.Socket 命名空间。利用该类我们可以直接编写Socket的客户端和服务的的程序了,
这里我们只讲tpc协议下的Socket编程。
TCP Socket连接的过程可以简单的分为:①.服务端监听 ②.客户端请求 ③.建立连接,
在服务端:
(1)声明一个套接字(称为监听套接字)Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
(2)声明一个端点(EndPoint)上面提到过Socket需要跟它绑定才能通信。IPEndPoint endPoint = new IPEndPoint(IPAddress.Loopback, 8080);
(3)设置监听队列serverSocket.Listen(100);
(4)通过Accept()方法来获取一个通信套接字(当有客户端连接时),这个方法会阻塞线程,避免界面卡死的现象,启动一个线程,把这个Accept()放在线程函数里面。
在客户端:
(1)声明一个套接字,通过connect()向服务器发起连接。
(2)通过Receive方法获取服务器发来的消息(这里同样启用一个线程,通过while循环来实时监听服务器端发送的消息)
注意:数据是以字节流(Byte[])的形式传递的,我会使用Encoding.UTF8.GetString()方法来获取为字符串。都是通过Send()来向彼此发送消息。
下面我们通过直接使用Socket类来构建一个简单的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 WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress ip = IPAddress.Any;
IPEndPoint duan = new IPEndPoint(ip, 55555);
s.Bind(duan);
textBox3.Text = "监听成功\n";
//设置在同一时间点内连接的数量
s.Listen(10);
//等待用户连接
Thread t = new Thread(A);
t.IsBackground = true;
t.Start(s);
}
Socket socketsend;
Dictionary<string, Socket> dic = new Dictionary<string, Socket>();
void A(object o)
{
while (true)
{
Socket s = o as Socket;
socketsend = s.Accept();
string name = socketsend.RemoteEndPoint.ToString();
dic.Add(name, socketsend);
comboBox1.Items.Add(name);
textBox3.AppendText("连接成功\n" + name + "\n");
Thread tt = new Thread(b);
tt.Start(socketsend);
}
}
private void Form1_Load(object sender, EventArgs e)
{
Control.CheckForIllegalCrossThreadCalls = false;
}
public void b(object oo)
{
Socket socketsend = oo as Socket;
while (true)
{
byte[] b = new byte[1024 * 1024 * 2];
int a = socketsend.Receive(b);
if (a == 0)
{
break;
}
string receive = Encoding.Default.GetString(b, 0, a);
textBox3.AppendText(receive + "\n");
}
}
private void button2_Click(object sender, EventArgs e)
{
byte[] by= System.Text.Encoding.Default.GetBytes(textBox4.Text);
List<byte> b = new List<byte>();
b.Add(0);
b.AddRange(by);
byte []cc= b.ToArray();
dic[comboBox1.SelectedItem.ToString()].Send(cc);
//socketsend.Send(by);
}
private void button3_Click(object sender, EventArgs e)
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Title = "请选择文件";
dialog.InitialDirectory = @"C:\Users\PC\Desktop";
dialog.Filter = "所有文件|*.*";
dialog.ShowDialog();
string name= dialog.FileName;
textBox5.Text = name;
}
private void button5_Click(object sender, EventArgs e)
{
using (FileStream f = new FileStream(textBox5.Text, FileMode.Open, FileAccess.Read))
{
byte[] b = new byte[1024 * 1024 * 5];
int r = f.Read(b, 0, b.Length);
List<byte> list = new List<byte>();
list.Add(1);
list.AddRange(b);
byte[] newby = list.ToArray();
dic[comboBox1.SelectedItem.ToString()].Send(newby, 0, r + 1, SocketFlags.None);
}
}
private void button4_Click(object sender, EventArgs e)
{
byte[] a = new byte[1];
a[0] = 2;
dic[comboBox1.SelectedItem.ToString()].Send(a);
}
}
}

下面是客户端代码。。
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;
using System.IO;
namespace WindowsFormsC
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Socket ss;
private void button1_Click(object sender, EventArgs e)
{
ss = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress ip = IPAddress.Parse(textBox1.Text);
IPEndPoint duan = new IPEndPoint(ip, Convert.ToInt32( textBox2.Text));
ss.Connect(duan);
a("连接服务端成功");
Thread t = new Thread(b);
t.Start();
}
void b()
{
while (true)
{
byte[] cc = new byte[1024 * 1024 * 2];
int ac = ss.Receive(cc);
if (ac == 0)
{
break;
}
if (cc[0]==0)
{
a(Encoding.Default.GetString(cc,1, ac-1));
//0 a length
}
else if (cc[0]==1)
{
SaveFileDialog dia = new SaveFileDialog();
dia.Title = "请保存文件";
dia.InitialDirectory = @"C:\Users\PC\Desktop";
dia.Filter = "所有文件|*.*";
dia.ShowDialog(this);
using (FileStream s=new FileStream (dia.FileName,FileMode.OpenOrCreate,FileAccess.Write))
{
s.Write(cc,0,ac-1);
MessageBox.Show("保存成功","提示");
}
}
else if (cc[0]==2)
{
for (int i = 0; i < 1000; i++)
{
this.Location = new Point(200, 200);
this.Location = new Point(250, 250);
}
}
}
}
void a(string name)
{
textBox3.AppendText(name + "\t\n");
}
private void button2_Click(object sender, EventArgs e)
{
byte[] v = Encoding.Default.GetBytes(textBox4.Text);
ss.Send(v);
}
private void Form1_Load(object sender, EventArgs e)
{
Control.CheckForIllegalCrossThreadCalls = false;
}
}
}

小程序的功能可以发消息,震动,传输文件、、。。。
大家可以加 编程学习交流 qq群 68363936~!!!
来源:https://www.cnblogs.com/asd362/p/4224662.html