C#模拟服务端客户端小程序
服务端:
主要功能:
- 对客户端的连接申请进行实时监听
- 对客户端发出的请求实时监听
- 对客户端进行交互(和客户端互发消息、向客户端发送文件,向客户端发出窗口抖动)
主要界面:
在这里插入图片描述
代码:
public partial class Form1 : Form
{
private Socket responseClientSocket;
//保存客户端的IP地址和对应是Socket
private Dictionary<string, Socket> dict = new Dictionary<string, Socket>();
//定义一个byte类型的泛型集合来保存发送的消息类型:0--文本类型,1--文件,2--震动
private List<byte> list;
public Form1()
{
InitializeComponent();
}
private void button6_Click(object sender, EventArgs e)
{
try
{
//当点击开始监听的时候 在服务器端创建一个负责监听IP地址跟端口号的Socket
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress iPAddress = IPAddress.Any;
//创建端口号对象
IPEndPoint iPEndPoint = new IPEndPoint(iPAddress, Convert.ToInt32(textBox2.Text));
//监听
socket.Bind(iPEndPoint);
ShowMsg("监听成功");
//同一时间只能10个客户端提出申请
socket.Listen(10);
//创建线程来监听连接服务端的客户端
Thread threadListen = new Thread(Listener);
threadListen.IsBackground = true;
threadListen.Start(socket);
}
catch
{
}
}
private void Listener(object obj)
{
Socket socket = obj as Socket;
while (true)
{
try
{
//负责响应客户端的socket
responseClientSocket = socket.Accept();
//保存当前的客户端IP地址和对应Socket
dict.Add(responseClientSocket.RemoteEndPoint.ToString(), responseClientSocket);
//将当前客户端的IP地址放到下拉框中
comboBox1.Items.Add(responseClientSocket.RemoteEndPoint.ToString());
ShowMsg(responseClientSocket.RemoteEndPoint.ToString() + ":连接成功");
//创建一个线程来接收客户端发出的请求
Thread threadRecive = new Thread(Recive);
threadRecive.IsBackground = true;
threadRecive.Start(responseClientSocket);
}
catch
{
}
}
}
/// <summary>
/// 接收客户端的请求
/// </summary>
/// <param name="obj"></param>
private void Recive(object obj)
{
while (true)
{
try
{
Socket reciveSocket = obj as Socket;
byte[] byteNews = new byte[1024 * 1024];
int result = reciveSocket.Receive(byteNews);
string reciveNews = Encoding.UTF8.GetString(byteNews, 0, result);
ShowMsg(reciveSocket.RemoteEndPoint.ToString() + ":" + reciveNews);
//如果客户端关闭\下线,则服务端就结束接收客户端的请求
if (result == 0)
{
break;
}
}
catch
{
}
}
}
private void ShowMsg(string str)
{
textBox3.AppendText(str + "\r\n");
}
private void Form1_Load(object sender, EventArgs e)
{
Control.CheckForIllegalCrossThreadCalls = false;
}
/// <summary>
/// 向客户端发送信息
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button4_Click(object sender, EventArgs e)
{
try
{
list = new List<byte>();
byte[] sendNews = Encoding.UTF8.GetBytes(textBox4.Text);
//responseClientSocket.Send(sendNews);
//byte集合首位定义为1是告书客户端服务端发送的是文本消息
list.Add(0);
//将需要发送的类容添加到集合中
list.AddRange(sendNews);
//将集合转换为数组发送给客户端
dict[comboBox1.SelectedItem.ToString()].Send(list.ToArray());
textBox4.Clear();
textBox4.Focus();
}
catch
{
}
}
private void button2_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Title = "请选择需要发送的文件";
openFileDialog.InitialDirectory = @"G:\Desktop";
openFileDialog.Filter = "所有文件|*.*";
openFileDialog.ShowDialog();
//显示选择文件的路径
textBox5.Text = openFileDialog.FileName;
}
/// <summary>
/// 向客户端发送文件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button3_Click(object sender, EventArgs e)
{
try
{
if (textBox5.Text == "")
{
MessageBox.Show("请选择要发送的文件!");
}
else
{
using (FileStream fsRead = new FileStream(textBox5.Text, FileMode.OpenOrCreate, FileAccess.Read))
{
byte[] buffer = new byte[1024 * 1024];
list = new List<byte>();
int cow = fsRead.Read(buffer, 0, buffer.Length);
//集合中首个元素为客户端传输的类型:0-文本类型,1-文件类型,2-向客户端发出了一个窗口抖动
list.Add(1);
//将选择文件读到list泛型集合中
list.AddRange(buffer);
//将泛型集合转换为byte数组
byte[] newBuffer = list.ToArray();
responseClientSocket.Send(newBuffer, 0, cow + 1, SocketFlags.None);
}
}
}
catch
{
}
}
/// <summary>
/// 向客户端发去窗口抖动
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button5_Click(object sender, EventArgs e)
{
try
{
list = new List<byte>();
list.Add(2);
byte[] newBuffer = list.ToArray();
responseClientSocket.Send(newBuffer);
}
catch
{
}
}
}
客户端
主要功能:
- 连接服务端
- 向服务端发出请求
- 接收服务端发来的消息
- 保存文件
- 窗口抖动
主要界面:
代码:
public partial class Form1 : Form
{
private Socket socket;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
//向服务端通信的Socket
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//将控件中的文本转换为IP地址
IPAddress ip = IPAddress.Parse(textBox1.Text);
IPEndPoint iPEndPoint = new IPEndPoint(ip, Convert.ToInt32(textBox2.Text));
//连接服务端
socket.Connect(iPEndPoint);
ShowMsg("连接成功");
//新建一个线程接收服务端发送的消息
Thread threadRecive = new Thread(Recive);
threadRecive.IsBackground = true;
threadRecive.Start();
}
catch
{
}
}
void ShowMsg(string str)
{
textBox3.AppendText(str + "\r\n");
}
/// <summary>
/// 向服务端发出请求
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button2_Click(object sender, EventArgs e)
{
try
{
byte[] byteNews = Encoding.UTF8.GetBytes(textBox4.Text);
socket.Send(byteNews);
textBox4.Clear();
textBox4.Focus();
}
catch
{
}
}
void Recive()
{
try
{
while (true)
{
byte[] buffer = new byte[1024 * 1024*5];
int num = socket.Receive(buffer);
//如果buffer[0]=0--表示服务端发送的文本信息
//buffer[0]==1--表示服务端发送的是文件
//buffer[0]==2--表示服务端发送的是窗口抖动
if (num == 0)
{
break;
}
if (buffer[0] == 0)
{
ShowMsg(socket.RemoteEndPoint.ToString() + ":" + Encoding.UTF8.GetString(buffer, 1, num - 1));
}
else if (buffer[0] == 1)
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Title = "请选择要保存文件路径";
saveFileDialog.InitialDirectory = @"G:\Desktop";
saveFileDialog.Filter = "所有文件|*.*";
saveFileDialog.ShowDialog(this);
using (FileStream fsWrite = new FileStream(saveFileDialog.FileName, FileMode.OpenOrCreate, FileAccess.Write))
{
fsWrite.Write(buffer, 1, num - 1);
}
MessageBox.Show("保存成功");
}
else
{
ZhenDong();
}
}
}
catch
{
}
}
private void Form1_Load(object sender, EventArgs e)
{
Control.CheckForIllegalCrossThreadCalls = false;
}
/// <summary>
/// 当服务端发出震动请求时,客户端调用此方法进行窗口震动
/// </summary>
void ZhenDong()
{
for (int i = 0; i < 3; i++)
{
this.Location = new Point(this.Location.X + 18, this.Location.Y + 18);
this.Location = new Point(this.Location.X + 28, this.Location.Y + 28);
}
}
}