实例介绍
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 SocketTCP
{
//声明委托
delegate void AddOnLineDelegate(string str, bool bl);
//声明委托
delegate void RecMsgDelegate(string str);
public partial class FrmTCPServer : Form
{
public FrmTCPServer()
{
InitializeComponent();
myAddOnline = AddOnline;
myRcvMsg = RecMsg;
myFileSave = FileSave;
}
//创建套接字
Socket sock = null;
//创建负责监听客户端连接的线程
Thread threadListen = null;
//创建URL与Socket的字典集合
Dictionary<string, Socket> DicSocket = new Dictionary<string, Socket>();
AddOnLineDelegate myAddOnline;
RecMsgDelegate myRcvMsg;
FileSaveDelegate myFileSave;
#region 开始监听
/// <summary>
/// 开始监听
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btn_StartServer_Click(object sender, EventArgs e)
{
//创建负责监听的套接字,注意其中参数:IPV4 字节流 TCP
sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress address = IPAddress.Parse(this.txt_IP.Text.Trim());
//根据IPAddress以及端口号创建IPE对象
IPEndPoint endpoint = new IPEndPoint(address, int.Parse(this.txt_Port.Text.Trim()));
try
{
sock.Bind(endpoint);
Invoke(myRcvMsg, "服务器开启成功!");
MessageBox.Show("开启服务成功!", "打开服务");
}
catch (Exception ex)
{
MessageBox.Show("开启服务失败" ex.Message, "打开服务");
return;
}
sock.Listen(10);
threadListen = new Thread(ListenConnecting);
threadListen.IsBackground = true;
threadListen.Start();
this.btn_StartServer.Enabled = false;
}
#endregion
#region 监听线程
/// <summary>
/// 监听线程
/// </summary>
private void ListenConnecting()
{
while (true)
{
//一旦监听到一个客户端的连接,将会创建一个与该客户端连接的套接字
Socket sockClient = sock.Accept();
string client = sockClient.RemoteEndPoint.ToString();
DicSocket.Add(client, sockClient);
Invoke(myAddOnline, client, true);
Invoke(myRcvMsg, client "上线了!");
//开启接受线程
Thread thr = new Thread(ReceiveMsg);
thr.IsBackground = true;
thr.Start(sockClient);
}
}
#endregion
#region 接收线程
/// <summary>
/// 接收线程
/// </summary>
/// <param name="sockClient"></param>
private void ReceiveMsg(object sockClient)
{
Socket sckclient = sockClient as Socket;
while (true)
{
//定义一个2M缓冲区
byte[] arrMsgRec = new byte[1024 * 1024 * 2];
int length = -1;
try
{
length = sckclient.Receive(arrMsgRec);
}
catch (Exception)
{
string str = sckclient.RemoteEndPoint.ToString();
Invoke(myRcvMsg, str "下线了!");
//从列表中移除URL
Invoke(myAddOnline, str, false);
DicSocket.Remove(str);
break;
}
if (length == 0)
{
string str = sckclient.RemoteEndPoint.ToString();
Invoke(myRcvMsg, str "下线了!");
//从列表中移除URL
Invoke(myAddOnline, str, false);
DicSocket.Remove(str);
break;
}
else
{
if (arrMsgRec[0] == 0)
{
string strMsg = Encoding.UTF8.GetString(arrMsgRec, 1, length-1);
string Msg = "[接收] " sckclient.RemoteEndPoint.ToString() " " strMsg;
Invoke(myRcvMsg, Msg);
}
if (arrMsgRec[0] == 1)
{
Invoke(myFileSave, arrMsgRec,length);
}
}
}
}
#endregion
#region 委托方法体
private void AddOnline(string url, bool bl)
{
if (bl)
{
this.lbOnline.Items.Add(url);
}
else
{
this.lbOnline.Items.Remove(url);
}
}
private void RecMsg(string str)
{
this.txt_Rcv.AppendText(str Environment.NewLine);
}
private void FileSave(byte[] bt, int length)
{
try
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "word files(*.docx)|*.docx|txt files(*.txt)|*.txt|xls files(*.xls)|*.xls|All files(*.*)|*.*";
if (sfd.ShowDialog() == DialogResult.OK)
{
string fileSavePath = sfd.FileName;
using (FileStream fs = new FileStream(fileSavePath, FileMode.Create))
{
fs.Write(bt, 1, length - 1);
Invoke(new Action(() => this.txt_Rcv.AppendText("[保存] 保存文件成功" fileSavePath Environment.NewLine)));
}
}
}
catch (Exception ex)
{
MessageBox.Show("保存异常" ex.Message, "保存文件出现异常");
}
}
#endregion
#region 发送消息
/// <summary>
/// 发送消息
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btn_SendToSingle_Click(object sender, EventArgs e)
{
string StrMsg = this.txt_Send.Text.Trim();
byte[] arrMsg = Encoding.UTF8.GetBytes(StrMsg);
byte[] arrSend = new byte[arrMsg.Length 1];
arrSend[0] = 0;
Buffer.BlockCopy(arrMsg, 0, arrSend, 1, arrMsg.Length);
if (this.lbOnline.SelectedItems.Count == 0)
{
MessageBox.Show("请选择你要发送的对象!", "发送提示");
return;
}
else
{
foreach (string item in this.lbOnline.SelectedItems)
{
DicSocket[item].Send(arrSend);
string Msg = "[发送] " item " " StrMsg;
Invoke(myRcvMsg, Msg);
}
}
}
#endregion
#region 群发消息
/// <summary>
/// 群发消息
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btn_SendToAll_Click(object sender, EventArgs e)
{
string StrMsg = this.txt_Send.Text.Trim();
byte[] arrMsg = Encoding.UTF8.GetBytes(StrMsg);
byte[] arrSend = new byte[arrMsg.Length 1];
arrSend[0] = 0;
Buffer.BlockCopy(arrMsg, 0, arrSend, 1, arrMsg.Length);
foreach (string item in this.DicSocket.Keys)
{
DicSocket[item].Send(arrSend);
string Msg = "[发送] " item " " StrMsg;
Invoke(myRcvMsg, Msg);
}
Invoke(myRcvMsg, "[群发] 群发完毕!");
}
#endregion
#region 打开客户端
/// <summary>
/// 打开客户端
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btn_Client_Click(object sender, EventArgs e)
{
FrmTCPClient objFrm = new FrmTCPClient();
objFrm.Show();
}
#endregion
#region 选择文件
/// <summary>
/// 选择文件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btn_SelectFile_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.InitialDirectory = "D:\\";
if (ofd.ShowDialog() == DialogResult.OK)
{
this.txt_SelectFile.Text = ofd.FileName;
}
}
#endregion
#region 发送文件
/// <summary>
/// 发送文件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btn_SendFile_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(txt_SelectFile.Text))
{
MessageBox.Show("请选择您要发送的文件!", "发送文件提示");
return;
}
string online = this.lbOnline.Text.Trim();
if (string.IsNullOrEmpty(online))
{
MessageBox.Show("请选择您要发送的对象!", "发送文件提示");
return;
}
using (FileStream fs = new FileStream(txt_SelectFile.Text, FileMode.Open))
{
string filename = Path.GetFileName(txt_SelectFile.Text);
string StrMsg = "发送文件为:" filename;
byte[] arrMsg = Encoding.UTF8.GetBytes(StrMsg);
byte[] arrSend= new byte[arrMsg.Length 1];
arrSend[0] =0;
Buffer.BlockCopy(arrMsg, 0, arrSend, 1, arrMsg.Length);
DicSocket[online].Send(arrSend);
byte[] arrfileSend = new byte[1024 * 1024 * 2];
int length = fs.Read(arrfileSend, 0, arrfileSend.Length);
byte[] arrfile = new byte[length 1];
arrfile[0] = 1;
Buffer.BlockCopy(arrfileSend, 0, arrfile, 1, length);
DicSocket[online].Send(arrfile);
}
}
#endregion
}
}
小贴士
感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。
- 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
- 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
- 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
- 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。
关于好例子网
本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明
网友评论
我要评论