基于C#的Socket网络编程
服务端
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 _01serverFrm
{
public partial class serverFrm : Form
{
public serverFrm()
{
InitializeComponent();
}
/// <summary>
/// 1.服务端的socket绑定ip和端口号,设置监听队列listen后开始检查是否有网络连接到服务器,用accept();
/// 2.服务端用receive接收客服端发来的字节数组
/// 3.客户端通过connect连接到服务器后通过send发送字节数组到服务端
/// 4.服务器通过send()发送到客户端,客户端通过receive接收
/// 5.服务器通过设置下拉框给指定的客服端发送数据,用字典存储ip接口和socket的映射关系
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnListen_Click(object sender, EventArgs e)
{
Socket socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress ip = IPAddress.Any;
IPEndPoint point = new IPEndPoint(ip,Convert.ToInt32(txtPort.Text));
socketWatch.Bind(point);
socketWatch.Listen(10);
ShowMsg("监听成功!");
Thread th = new Thread(Listen);
th.IsBackground=true;
th.Start(socketWatch);
}
//Socket socketSend;
Dictionary<string,Socket> dicSocket = new Dictionary<string,Socket>();
void Listen(object o)
{
Socket socketWatch = o as Socket;
while (true)
{
Socket socketSend = socketWatch.Accept();
dicSocket.Add(socketSend.RemoteEndPoint.ToString(), socketSend);
cboAddress.Items.Add(socketSend.RemoteEndPoint.ToString());
cboAddress.SelectedIndex = 0;//设置该下拉框默认选中第一项。
ShowMsg(socketSend.RemoteEndPoint.ToString() + ":" + "连接成功");
Thread th = new Thread(Receive);
th.IsBackground = true;
th.Start(socketSend);
}
}
void Receive(object o)
{
Socket socketSend = o as Socket;
while (true)
{
byte[] buffer = new byte[1024];
int r = socketSend.Receive(buffer);
if (r == 0)
{
break;
}
string str = Encoding.UTF8.GetString(buffer, 0, r);
ShowMsg(socketSend.RemoteEndPoint.ToString() + ":" + str);
}
}
void ShowMsg(string str)
{
txtLog.AppendText(str + "\r\n");
}
private void serverFrm_Load(object sender, EventArgs e)
{
Control.CheckForIllegalCrossThreadCalls = false;
}
private void btnSend_Click(object sender, EventArgs e)
{
//byte[] buffer = new byte[1024]; 给数组宽度在下面添加到列表的时候按实际宽度来的,不合理,
byte[] buffer = Encoding.UTF8.GetBytes(txtConversation.Text);
List<byte> list = new List<byte>();
list.Add(0);
list.AddRange(buffer);
byte[] newBuffer = list.ToArray();
dicSocket[cboAddress.SelectedItem.ToString()].Send(newBuffer);//这里的key不能加双引号,报错了好多次了
txtConversation.Text = "";
}
private void btnChoose_Click(object sender, EventArgs e)
{
using (OpenFileDialog ofd = new OpenFileDialog() )
{
ofd.Title = "请选择文件";
ofd.ShowDialog();
txtFile.Text = ofd.FileName;
}
}
//List<byte> list = new List<byte>();
private void btnSendFile_Click(object sender, EventArgs e)
{
using (FileStream fs = new FileStream(txtFile.Text,FileMode.OpenOrCreate,FileAccess.Read))
{
byte[] buffer = new byte[1024*1024*3];
int r = fs.Read(buffer, 0, buffer.Length);
List<byte> list = new List<byte>();
list.Add(1);
list.AddRange(buffer);
byte[] newBuffer = list.ToArray();
dicSocket[cboAddress.SelectedItem.ToString()].Send(newBuffer, 0, r + 1, SocketFlags.None);
}
}
private void btnTremble_Click(object sender, EventArgs e)
{
byte[] buffer = new byte[1];
buffer[0] = 2;
dicSocket[cboAddress.SelectedItem.ToString()].Send(buffer);
}
}
}
客户端
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 _02clientFrm
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Socket socketConnection;
private void btnConnection_Click(object sender, EventArgs e)
{
socketConnection = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress ip = IPAddress.Parse(txtAddress.Text);
IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32(txtPort.Text));
socketConnection.Connect(point);
ShowMsg("连接成功,连接到"+socketConnection.RemoteEndPoint.ToString());
Thread th = new Thread(Receive);
th.IsBackground = true;
th.Start();
}
void ShowMsg(string str)
{
txtLog.AppendText(str + "\r\n");
}
private void btnSend_Click(object sender, EventArgs e)
{
byte[] buffer = new byte[1024];
buffer = Encoding.UTF8.GetBytes(txtConversation.Text);
socketConnection.Send(buffer);
txtConversation.Text = "";
}
void Receive()
{
while (true)
{
byte[] buffer = new byte[1024*1024*3];
int r = socketConnection.Receive(buffer);
if (r == 0)
{
break;
}
switch (buffer[0])
{
case 0:
string str = Encoding.UTF8.GetString(buffer, 1, r - 1);
ShowMsg(socketConnection.RemoteEndPoint.ToString() + ":" + str);
break;
case 1:
using (SaveFileDialog sfd = new SaveFileDialog())
{
sfd.ShowDialog(this); //客户端弹不出来,加个this
string strFileName = sfd.FileName;
using (FileStream fsWrite = new FileStream(strFileName, FileMode.OpenOrCreate, FileAccess.Write))
{
fsWrite.Write(buffer, 1, r - 1);
}
MessageBox.Show("保存成功");
}
break;
case 2:
Tremble();
break;
}
}
}
void Tremble()
{
for (int i = 0; i < 500; i++)
{
this.Location = new Point(0, 0);
this.Location = new Point(20, 20);
}
}
private void Form1_Load(object sender, EventArgs e)
{
Control.CheckForIllegalCrossThreadCalls = false;
}
}
}
标签:Socket,C#,void,编程,System,buffer,new,using,byte
From: https://www.cnblogs.com/wheniwasjustakid/p/16818802.html