博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[通信] C#多线程Socket-文件传输
阅读量:5311 次
发布时间:2019-06-14

本文共 6993 字,大约阅读时间需要 23 分钟。

//服务端

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;using System.Net; using System.Net.Sockets; using System.Threading; using System.Xml;  namespace Server {     public partial class ServerMain : Form     {         public ServerMain()         {             InitializeComponent();         }          private void ServerMain_Load(object sender, EventArgs e)         {             this.CmdStar.Enabled = true;             this.CmdStop.Enabled = false;         }          private void 配置参数ToolStripMenuItem_Click(object sender, EventArgs e)         {             Set TSet = new Set();             TSet.ShowDialog();         }          private void 关于ToolStripMenuItem_Click(object sender, EventArgs e)         {             About TAbout = new About();             TAbout.Show();         }         ///          /// 获得XML文件中的端口号         ///          /// 
private int GetPort() { try { XmlDocument TDoc = new XmlDocument(); TDoc.Load("Settings.xml"); string TPort = TDoc.GetElementsByTagName("ServerPort")[0].InnerXml; return Convert.ToInt32(TPort); } catch { return 6600; }//默认是6600 } //声明将要用到的类 private IPEndPoint ServerInfo;//存放服务器的IP和端口信息 private Socket ServerSocket;//服务端运行的SOCKET private Thread ServerThread;//服务端运行的线程 private Socket[] ClientSocket;//为客户端建立的SOCKET连接 private int ClientNumb;//存放客户端数量 private byte[] MsgBuffer;//存放消息数据 private void CmdStar_Click(object sender, EventArgs e) { ServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream,ProtocolType.Tcp); ServerInfo=new IPEndPoint(IPAddress.Any, this.GetPort()); ServerSocket.Bind(ServerInfo);//将SOCKET接口和IP端口绑定 ServerSocket.Listen(10);//开始监听,并且挂起数为10 ClientSocket = new Socket[65535];//为客户端提供连接个数 MsgBuffer = new byte[65535];//消息数据大小 ClientNumb = 0;//数量从0开始统计 ServerThread = new Thread(RecieveAccept);//将接受客户端连接的方法委托给线程 ServerThread.Start();//线程开始运行 CheckForIllegalCrossThreadCalls = false;//不捕获对错误线程的调用 this.CmdStar.Enabled = false; this.CmdStop.Enabled = true; this.StateMsg.Text = "服务正在运行" + " 运行端口:" + this.GetPort().ToString(); this.ClientList.Items.Add("服务于 " + DateTime.Now.ToString() + " 开始运行."); } //接受客户端连接的方法 private void RecieveAccept() { while (true) { ClientSocket[ClientNumb] = ServerSocket.Accept(); ClientSocket[ClientNumb].BeginReceive(MsgBuffer, 0, MsgBuffer.Length, 0, newAsyncCallback(RecieveCallBack),ClientSocket[ClientNumb]); this.ClientList.Items.Add(ClientSocket[ClientNumb].RemoteEndPoint.ToString()+"成功连接服务器."); ClientNumb++; } } //回发数据给客户端 private void RecieveCallBack(IAsyncResult AR) { try { Socket RSocket = (Socket)AR.AsyncState; int REnd = RSocket.EndReceive(AR); for (int i = 0; i

//客户端

//客户端 using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;using System.Net; using System.Net.Sockets;  namespace Client {    public partial class ClientMain : Form    {        public ClientMain()        {            InitializeComponent();        }        private IPEndPoint ServerInfo;        private Socket ClientSocket;        private Byte[] MsgBuffer;        private Byte[] MsgSend;        private void ClientMain_Load(object sender, EventArgs e)        {            this.CmdSend.Enabled = false;            this.CmdExit.Enabled = false;            ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);            MsgBuffer = new Byte[65535];            MsgSend = new Byte[65535];            CheckForIllegalCrossThreadCalls = false;            Random TRand = new Random();            this.UserName.Text = "用户" + TRand.Next(10000).ToString();        }        private void CmdEnter_Click(object sender, EventArgs e)        {            ServerInfo = new IPEndPoint(IPAddress.Parse(this.ServerIP.Text), Convert.ToInt32(this.ServerPort.Text));            try         {                 ClientSocket.Connect(ServerInfo);              ClientSocket.Send(Encoding.Unicode.GetBytes("用户: " + this.UserName.Text + " 进入系统!\n"));              ClientSocket.BeginReceive(MsgBuffer, 0, MsgBuffer.Length, 0, new AsyncCallback(ReceiveCallBack), null);              this.SysMsg.Text += "登录服务器成功!\n";                 this.CmdSend.Enabled = true;                 this.CmdEnter.Enabled = false;                 this.CmdExit.Enabled = true;             }         catch         {                 MessageBox.Show("登录服务器失败,请确认服务器是否正常工作!");             }        }        private void ReceiveCallBack(IAsyncResult AR)        {            try            {                int REnd = ClientSocket.EndReceive(AR);                this.RecieveMsg.AppendText(Encoding.Unicode.GetString(MsgBuffer, 0, REnd));                ClientSocket.BeginReceive(MsgBuffer, 0, MsgBuffer.Length, 0, new AsyncCallback(ReceiveCallBack), null);            }            catch            {                MessageBox.Show("已经与服务器断开连接!");                this.Close();            }        }        private void CmdSend_Click(object sender, EventArgs e)        {            MsgSend = Encoding.Unicode.GetBytes(this.UserName.Text + "说:\n" + this.SendMsg.Text + "\n");            if (ClientSocket.Connected)            {                 ClientSocket.Send(MsgSend);                 this.SendMsg.Text = "";             }         else         {                 MessageBox.Show("当前与服务器断开连接,无法发送信息!");             }        }        private void CmdExit_Click(object sender, EventArgs e)        {            if (ClientSocket.Connected)            {                ClientSocket.Send(Encoding.Unicode.GetBytes(this.UserName.Text + "离开了房间!\n"));                ClientSocket.Shutdown(SocketShutdown.Both);                 ClientSocket.Disconnect(false);             }             ClientSocket.Close();              this.CmdSend.Enabled = false;             this.CmdEnter.Enabled = true;             this.CmdExit.Enabled = false;         }          private void RecieveMsg_TextChanged(object sender, EventArgs e)         {             this.RecieveMsg.ScrollToCaret();         }          private void SendMsg_KeyDown(object sender, KeyEventArgs e)         {             if (e.Control && e.KeyValue == 13)             {                 e.Handled = true;                 this.CmdSend_Click(this, null);             }         }     } }

 

转载于:https://www.cnblogs.com/Areas/p/5665841.html

你可能感兴趣的文章
201671010439温永琴 实验三作业互评与改进
查看>>
Java笔记第六篇 数据类型初了解(上)
查看>>
00-自测5. Shuffling Machine (20)
查看>>
Python Base Five
查看>>
141. Linked List Cycle
查看>>
JAVA-初步认识-常用对象API(集合框架-Map集合-hashmap存储自定义对象)
查看>>
线程池的堆栈问题
查看>>
浅析C#中的事件
查看>>
static和extern关键字 对函数的作用
查看>>
2012.05.15
查看>>
python 数据分析2
查看>>
unity与android交互总结
查看>>
法线贴图是用来解决低模的细节表现问题
查看>>
echarts地图中城市与省份之间的切换
查看>>
Maven学习小结(四 聚合与继承)
查看>>
python_excel_读写(转载)
查看>>
Meanshift均值漂移算法
查看>>
[转载]JavaScript基础知识细节
查看>>
神经网络语言模型NNLM
查看>>
Unity3d Editor使用cs文件与Plugins dll文件冲突的问题
查看>>