图示:
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;
using System.Net.Sockets;
using System.Threading;
using System.IO;
namespace Client
{
public partial
class Client : Form
{
public Client()
{
InitializeComponent();
TextBox.CheckForIllegalCrossThreadCalls
=
false;
}
Thread threadClient
=
null;
//客户端负责监听服务端发来消息的线程
Socket socketClient
=
null;
//客户端套接字
private
void btnConnect_Click(
object sender, EventArgs e)
{
//获取IP
IPAddress address
= IPAddress.Parse(txtIP.Text.Trim());
//创建包含IP和端口的网络节点
IPEndPoint endpoint
=
new IPEndPoint(address,
int.Parse(txtPort.Text.Trim()));
//创建酷护短套接字
socketClient
=
new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//向指定的IP和端口发送连接请求
socketClient.Connect(endpoint);
//创建线程,监听服务端发来的消息
threadClient
=
new Thread(RecMsg);
//设置为后台线程
threadClient.IsBackground
=
true;
//执行线程
threadClient.Start();
}
/// <summary>
/// 监听服务端发来的消息
/// </summary>
void RecMsg()
{
while (
true)
{
//定义一个接收服务端数据的缓存区(2M字节数组)
byte[] arrMsgRec
=
new
byte[
1024
*
1024
*
2];
//将接收到的数据存入arrMsgRec数组,并返回真正接收到的数据的长度
int length
= socketClient.Receive(arrMsgRec);
//将接收到的服务端发来的消息转换成字符串(将所有元素【包含字符之外】转换)
string strMsgRec
= System.Text.Encoding.UTF8.GetString(arrMsgRec,
0,length);
//取有效数据
//显示接收到的消息
ShowMsg(strMsgRec);
}
}
/// <summary>
/// 在窗体文本框中显示消息
/// </summary>
/// <param name="msg"></param>
void ShowMsg(
string msg)
{
txtMsg.AppendText(msg
+
"
\r\n
");
}
private
void btnSendMsg_Click(
object sender, EventArgs e)
{
//获取需要传送的字符串
string strMsg
= txtMsgSend.Text.Trim();
//将字符串转换为方便网络传送的二进制数据
byte[] arrMsg
= System.Text.Encoding.UTF8.GetBytes(strMsg);
byte[] arrMsgSend
=
new
byte[arrMsg.Length
+
1];
arrMsgSend[
0]
=
0;
//0代表发送的是文字
Buffer.BlockCopy(arrMsg,
0, arrMsgSend,
1, arrMsg.Length);
//发送数据
socketClient.Send(arrMsgSend);
ShowMsg(
"
我说:
"
+ strMsg);
}
//选择要发送的文件
private
void txtChoseFile_Click(
object sender, EventArgs e)
{
OpenFileDialog ofd
=
new OpenFileDialog();
if (ofd.ShowDialog()
== System.Windows.Forms.DialogResult.OK)
{
txtFilePath.Text
= ofd.FileName;
}
}
//向服务端发送文件
private
void txtSendFile_Click(
object sender, EventArgs e)
{
//用文件流打开用户选择的文件
using (FileStream fs
=
new FileStream(txtFilePath.Text, FileMode.Open))
{
byte[] arrFile
=
new
byte[
1024
*
1024
*
2];
//定义一个2M的缓存区
//将文件数据读到数组中,并获取读取的真实数据长度length
int length
= fs.Read(arrFile,
0, arrFile.Length);
byte[] arrFileSend
=
new
byte[length
+
1];
arrFileSend[
0]
=
1;
//代表发送的是文件
//将arrFile里的元素从第0个开始,拷贝到arrFileSend数组里,从第一个位置开始存放,一共拷贝length格数据
Buffer.BlockCopy(arrFile,
0, arrFileSend,
1, length);
//发送包含了标识位的新数据数组到服务端
socketClient.Send(arrFileSend);
}
}
}
}