
【服务器】
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.Windows.Forms; namespace SocketDemo
{
public partial class Server : Form
{
private Socket socketSend; public Server()
{
InitializeComponent(); }
private void Form1_Load(object sender, EventArgs e)
{
Control.CheckForIllegalCrossThreadCalls = false;
this.filePath.ReadOnly = true;
} private void button1_Click(object sender, EventArgs e)
{
try
{
//当点击开始监听时,在服务器端创建一个负责监听的ip地址和端口号
Socket socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress ip = IPAddress.Any;
//创建一个端口号
IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32(this.portNum.Text));
//创建监听
socketWatch.Bind(point);
ShowMessage("监听成功!");
socketWatch.Listen();
//等待客户端的链接,并且创建一个负责通信的socket
Thread thread = new Thread(Listen);
thread.IsBackground = true;
thread.Start(socketWatch);
}
catch (Exception)
{
}
} Dictionary<string, Socket> dic = new Dictionary<string, Socket>(); /// <summary>
/// 等待客户端链接,创建与之通信的scoket
/// </summary>
private void Listen(object o)
{
Socket socketWatch = o as Socket;
while (true)
{
try
{
//等待客户端的连接
socketSend = socketWatch.Accept();
//将连接过来的客户端存储至Dictionary和下拉框中,以便区分是哪个客户端
dic.Add(socketSend.RemoteEndPoint.ToString(), socketSend);
//将ip和端口号存入下拉框中
dropList.Items.Add(socketSend.RemoteEndPoint.ToString());
ShowMessage($"{socketSend.RemoteEndPoint.ToString()}:连接成功!");
//另外再开一个线程不停地接收客户端发来的消息
Thread thread = new Thread(Receive);
thread.IsBackground = true;
thread.Start(socketSend);
}
catch (Exception)
{
}
}
} /// <summary>
/// 服务器不停地接收客户端发来的消息
/// </summary>
/// <param name="obj"></param>
private void Receive(object obj)
{
Socket socketSend = obj as Socket;
while (true)
{
try
{
//服务器应该接收客户端发来的消息
byte[] buffer = new byte[ * ];
//实际接收的有效字节数
int num = socketSend.Receive(buffer);
//判断接收的字节是否为0,如果为0,则表明客户端已经下线
if (num == )
{
break;
}
string str = Encoding.UTF8.GetString(buffer, , num);
ShowMessage($"{socketSend.RemoteEndPoint}:{str}");
}
catch (Exception)
{
}
}
}
private void ShowMessage(string str)
{
this.textListen.AppendText($"{str}\r\n");
} /// <summary>
/// 服务器发送消息给客户端
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button2_Click(object sender, EventArgs e)
{
if (dropList.Text == "---请选择---")
{
MessageBox.Show("请先选择您要发送的客户端");
return;
}
if (this.serverMsg.Text.Trim() == "" && this.filePath.Text.Trim() == "")
{
MessageBox.Show("请输入信息或选择文件");
return;
}
List<byte> list = new List<byte>(); if (this.serverMsg.Text.Trim() != "" && this.filePath.Text.Trim() == "")
{
byte[] buffer = Encoding.UTF8.GetBytes(this.serverMsg.Text.Trim());
//给发送的内容添加前缀,如果加0,则表示发消息
list.Add();
list.AddRange(buffer);
byte[] newBuffer = list.ToArray();
dic[dropList.SelectedItem.ToString().Trim()].Send(newBuffer);
}
else if (this.filePath.Text.Trim() != "" && this.serverMsg.Text.Trim() == "")
{
using (FileStream fs = new FileStream(filePath.Text.Trim(), FileMode.Open, FileAccess.Read))
{
byte[] by = new byte[ * * ];
int length = fs.Read(by, , by.Length);
//给发送的内容添加前缀,如果加1,则表示发文件
list.Add();
list.AddRange(by);
byte[] newBy = list.ToArray();
dic[dropList.SelectedItem.ToString().Trim()].Send(newBy, , length + , SocketFlags.None);
}
}
else
{
MessageBox.Show("只能是发送消息或传输文件中的一项");
}
} /// <summary>
/// 打开所需的文件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void openFile_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.InitialDirectory = @"C:\Users\Administrator\Desktop";
ofd.Title = "打开文件";
ofd.Filter = "所有文件|*.*";
ofd.ShowDialog();
this.filePath.Text = ofd.FileName;
}
}
}
【客户端】
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.Windows.Forms; namespace 客户端
{
public partial class Client : Form
{
public Client()
{
InitializeComponent();
} private void Form1_Load(object sender, EventArgs e)
{
Control.CheckForIllegalCrossThreadCalls = false;
} Socket socketSend;
private void button1_Click(object sender, EventArgs e)
{
try
{
//创建一个负责通信的socket
socketSend = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress ip = IPAddress.Parse(this.IpMess.Text.Trim());
IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32(this.clientPort.Text.Trim()));
socketSend.Connect(point);
ShowMess("连接成功!");
//创建线程接收消息
Thread th = new Thread(Receive);
th.IsBackground = true;
th.Start();
}
catch (Exception)
{
MessageBox.Show("可能是因为没有启动服务器监听!");
}
}
private void Receive()
{
while (true)
{
try
{
byte[] buffer = new byte[ * * ]; //最长10M
//通过字节二进制来接收消息,获取字节长度
int length = socketSend.Receive(buffer);
if (length == )
{
break;
}
//如果为0接收消息
if (buffer[]==)
{
//去掉前缀
string str = Encoding.UTF8.GetString(buffer, , length-);
ShowMess(socketSend.RemoteEndPoint + ":" + str);
}
//如果为1接收文件
else if (buffer[]==)
{
//保存文件
SaveFileDialog sfd = new SaveFileDialog();
sfd.InitialDirectory = @"C:\Users\Administrator\Desktop";
sfd.Title = "选择文件";
sfd.Filter = "所有文件|*.*";
//弹出对话窗
sfd.ShowDialog(this);
using (var fs=new FileStream(sfd.FileName,FileMode.OpenOrCreate,FileAccess.Write))
{
fs.Write(buffer, , length - );
}
MessageBox.Show("保存成功");
}
}
catch (Exception)
{
}
}
}
private void ShowMess(string str)
{
this.clientMess.AppendText($"{str}\r\n");
} private void clientMess_TextChanged(object sender, EventArgs e)
{ } /// <summary>
/// 客户端给服务器发送消息
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void sendBtn_Click(object sender, EventArgs e)
{
byte[] buffer = Encoding.UTF8.GetBytes(this.sendMsg.Text.Trim());
socketSend.Send(buffer);
}
}
}