├── .gitignore ├── README.md ├── TCPClient ├── Program.cs ├── Properties │ ├── AssemblyInfo.cs │ ├── Resources.Designer.cs │ ├── Resources.resx │ ├── Settings.Designer.cs │ └── Settings.settings ├── TCPClient.csproj ├── frmCreateTCPClient.Designer.cs ├── frmCreateTCPClient.cs ├── frmCreateTCPClient.resx ├── frmTCPClient.Designer.cs ├── frmTCPClient.cs └── frmTCPClient.resx ├── TCPServer ├── Program.cs ├── Properties │ ├── AssemblyInfo.cs │ ├── Resources.Designer.cs │ ├── Resources.resx │ ├── Settings.Designer.cs │ └── Settings.settings ├── TCPServer.csproj ├── frmCreateTCPServer.Designer.cs ├── frmCreateTCPServer.cs ├── frmCreateTCPServer.resx ├── frmTCPServer.Designer.cs ├── frmTCPServer.cs └── frmTCPServer.resx ├── TJSYXY.Communication.sln ├── TJSYXY.Communication.suo ├── TJSYXY.Communication ├── Msg.cs ├── Properties │ └── AssemblyInfo.cs ├── TCP │ ├── TCPClient.cs │ ├── TCPClientManager.cs │ ├── TCPEndPoint.cs │ ├── TCPServer.cs │ ├── TCPServerManager.cs │ └── TCPs.cs ├── TJSYXY.Communication.csproj ├── UDP │ ├── UDPClient.cs │ ├── UDPClientManager.cs │ └── UDPs.cs ├── ZMessage.cs └── ZMessageStream.cs ├── UDPClient ├── Program.cs ├── Properties │ ├── AssemblyInfo.cs │ ├── Resources.Designer.cs │ ├── Resources.resx │ ├── Settings.Designer.cs │ └── Settings.settings ├── UDPClient.csproj ├── frmCreateUDPClient.Designer.cs ├── frmCreateUDPClient.cs ├── frmCreateUDPClient.resx ├── frmUDPClient.Designer.cs ├── frmUDPClient.cs └── frmUDPClient.resx ├── file_structure.png ├── multiple_tcp_client.png ├── multiple_tcp_server.png └── multiple_udp_client.png /.gitignore: -------------------------------------------------------------------------------- 1 | ################# 2 | ## Eclipse 3 | ################# 4 | 5 | *.pydevproject 6 | .project 7 | .metadata 8 | bin/ 9 | tmp/ 10 | *.tmp 11 | *.bak 12 | *.swp 13 | *~.nib 14 | local.properties 15 | .classpath 16 | .settings/ 17 | .loadpath 18 | 19 | # External tool builders 20 | .externalToolBuilders/ 21 | 22 | # Locally stored "Eclipse launch configurations" 23 | *.launch 24 | 25 | # CDT-specific 26 | .cproject 27 | 28 | # PDT-specific 29 | .buildpath 30 | 31 | 32 | ################# 33 | ## Visual Studio 34 | ################# 35 | 36 | ## Ignore Visual Studio temporary files, build results, and 37 | ## files generated by popular Visual Studio add-ons. 38 | 39 | # User-specific files 40 | *.suo 41 | *.user 42 | *.sln.docstates 43 | 44 | # Build results 45 | 46 | [Dd]ebug/ 47 | [Rr]elease/ 48 | x64/ 49 | build/ 50 | [Bb]in/ 51 | [Oo]bj/ 52 | 53 | # MSTest test Results 54 | [Tt]est[Rr]esult*/ 55 | [Bb]uild[Ll]og.* 56 | 57 | *_i.c 58 | *_p.c 59 | *.ilk 60 | *.meta 61 | *.obj 62 | *.pch 63 | *.pdb 64 | *.pgc 65 | *.pgd 66 | *.rsp 67 | *.sbr 68 | *.tlb 69 | *.tli 70 | *.tlh 71 | *.tmp 72 | *.tmp_proj 73 | *.log 74 | *.vspscc 75 | *.vssscc 76 | .builds 77 | *.pidb 78 | *.log 79 | *.scc 80 | 81 | # Visual C++ cache files 82 | ipch/ 83 | *.aps 84 | *.ncb 85 | *.opensdf 86 | *.sdf 87 | *.cachefile 88 | 89 | # Visual Studio profiler 90 | *.psess 91 | *.vsp 92 | *.vspx 93 | 94 | # Guidance Automation Toolkit 95 | *.gpState 96 | 97 | # ReSharper is a .NET coding add-in 98 | _ReSharper*/ 99 | *.[Rr]e[Ss]harper 100 | 101 | # TeamCity is a build add-in 102 | _TeamCity* 103 | 104 | # DotCover is a Code Coverage Tool 105 | *.dotCover 106 | 107 | # NCrunch 108 | *.ncrunch* 109 | .*crunch*.local.xml 110 | 111 | # Installshield output folder 112 | [Ee]xpress/ 113 | 114 | # DocProject is a documentation generator add-in 115 | DocProject/buildhelp/ 116 | DocProject/Help/*.HxT 117 | DocProject/Help/*.HxC 118 | DocProject/Help/*.hhc 119 | DocProject/Help/*.hhk 120 | DocProject/Help/*.hhp 121 | DocProject/Help/Html2 122 | DocProject/Help/html 123 | 124 | # Click-Once directory 125 | publish/ 126 | 127 | # Publish Web Output 128 | *.Publish.xml 129 | *.pubxml 130 | *.publishproj 131 | 132 | # NuGet Packages Directory 133 | ## TODO: If you have NuGet Package Restore enabled, uncomment the next line 134 | #packages/ 135 | 136 | # Windows Azure Build Output 137 | csx 138 | *.build.csdef 139 | 140 | # Windows Store app package directory 141 | AppPackages/ 142 | 143 | # Others 144 | sql/ 145 | *.Cache 146 | ClientBin/ 147 | [Ss]tyle[Cc]op.* 148 | ~$* 149 | *~ 150 | *.dbmdl 151 | *.[Pp]ublish.xml 152 | *.pfx 153 | *.publishsettings 154 | 155 | # RIA/Silverlight projects 156 | Generated_Code/ 157 | 158 | # Backup & report files from converting an old project file to a newer 159 | # Visual Studio version. Backup files are not needed, because we have git ;-) 160 | _UpgradeReport_Files/ 161 | Backup*/ 162 | UpgradeLog*.XML 163 | UpgradeLog*.htm 164 | 165 | # SQL Server files 166 | App_Data/*.mdf 167 | App_Data/*.ldf 168 | 169 | ############# 170 | ## Windows detritus 171 | ############# 172 | 173 | # Windows image file caches 174 | Thumbs.db 175 | ehthumbs.db 176 | 177 | # Folder config file 178 | Desktop.ini 179 | 180 | # Recycle Bin used on file shares 181 | $RECYCLE.BIN/ 182 | 183 | # Mac crap 184 | .DS_Store 185 | 186 | 187 | ############# 188 | ## Python 189 | ############# 190 | 191 | *.py[cod] 192 | 193 | # Packages 194 | *.egg 195 | *.egg-info 196 | dist/ 197 | build/ 198 | eggs/ 199 | parts/ 200 | var/ 201 | sdist/ 202 | develop-eggs/ 203 | .installed.cfg 204 | 205 | # Installer logs 206 | pip-log.txt 207 | 208 | # Unit test / coverage reports 209 | .coverage 210 | .tox 211 | 212 | #Translations 213 | *.mo 214 | 215 | #Mr Developer 216 | .mr.developer.cfg 217 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # TJSYXYCommunication 2 | a simple tcp/udp communication framework,support us to create multi-server(multi-client) with simple steps. 3 | 4 | see more: http://www.cnblogs.com/xiaozhi_5638/p/4666957.html 5 | 6 | - **file structure** 7 | 8 | ![](https://github.com/sherlockchou86/TJSYXYCommunication/blob/master/file_structure.png) 9 | 10 | - **manage multiple sockets in tcp server** 11 | 12 | ![](https://github.com/sherlockchou86/TJSYXYCommunication/blob/master/multiple_tcp_server.png) 13 | 14 | - **manage multiple sockets in tcp client** 15 | 16 | ![](https://github.com/sherlockchou86/TJSYXYCommunication/blob/master/multiple_tcp_client.png) 17 | 18 | - **manage multiple sockets in udp client** 19 | 20 | ![](https://github.com/sherlockchou86/TJSYXYCommunication/blob/master/multiple_udp_client.png) 21 | 22 | ### TCPServer 23 | - **Create a server** 24 | 25 | TCPServerManager manager = new TCPServerManager("RegisterServer"); 26 | 27 | - **Start a server** 28 | 29 | TCPServerManager manager = new TCPServerManager("RegisterServer"); 30 | manager.Start(9090); 31 | 32 | - **Register events** 33 | 34 | TCPServerManager manager = new TCPServerManager("RegisterServer"); 35 | manager.TCPClientConnected += new TCPClientConnectedEventHandler(); 36 | manager.TCPClientDisConnected += new TCPClientDisConnectedEventHandler(); 37 | manager.TCPMessageReceived += new TCP MessageReceivedEventHandler(); 38 | 39 | - **Deal eessages(Event handlers)** 40 | 41 | private void manager_TCPMessageReceived(string csID, TCPMessageRecivedEventArgs args) 42 | { 43 | //csID indicates the server which activated the event(because of multiple servers). 44 | //args.Msg indicates the Message type we received,a Msg enum type. 45 | //args.Data indicates the Message data,byte[] type. 46 | //args.Time indicates the time when we received the message. 47 | //args.End indicates the remote endpoint who sent the message, TCPEndPoint type. 48 | } 49 | 50 | ### TCPCLient 51 | - **Create a client** 52 | 53 | TCPClientManager manager = new TCPClientManager("RegisterClient"); 54 | 55 | - **Connect the server** 56 | 57 | TCPClientManager manager = new TCPClientManager("RegisterClient"); 58 | manager.Connect("10.0.1.10",8090); //connect to server 59 | 60 | - **Register events** 61 | 62 | TCPClientManager manager = new TCPClientManager("RegisterClient"); 63 | manager.TCPMessageReceived += new TCPMessageReceivedEventHandler(); 64 | 65 | - **Deal messages(Event handlers)** 66 | 67 | > the same with tcp server. 68 | 69 | ### UDPClient 70 | - **Create a client** 71 | 72 | UDPClientManager manager = new UDPClientManager("WeatherMessage"); 73 | 74 | - **Listen the port** 75 | 76 | UDPClientManager manager = new UDPClientManager("WeatherMessage"); 77 | manager.Start(9000); //listen the 9000, receive weather message 78 | //... 79 | UDPClientManager manager = new UDPClientManager("Radar"); 80 | manager.Start(9001); //listen the 9001, receive radar data 81 | 82 | - **Register events** 83 | 84 | UDPClientManager manager = new UDPClientManager("WeatherMessage"); 85 | manager.UDPMessageReceived += new UDPMessageReceivedEventHandler(); 86 | 87 | - **Deal messages(Event handlers)** 88 | 89 | private void manager_UDPMessageReceived(string csID, UDPMessageReceivedEventArgs args) 90 | { 91 | //csID indicates the client which activated the event(because of multiple clients) 92 | //args.Msg indicates th message type, Msg enum type. 93 | //args.Data indicates the message data, byte[] type. 94 | //args.Time indicates the time when we received the message. 95 | //args.RemoteIP indicates the ip who sent the message. 96 | //args.RemotePort indicates the port who sent the message. 97 | } 98 | 99 | 100 | 101 | -------------------------------------------------------------------------------- /TCPClient/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Windows.Forms; 5 | 6 | namespace TCPClient 7 | { 8 | static class Program 9 | { 10 | /// 11 | /// The main entry point for the application. 12 | /// 13 | [STAThread] 14 | static void Main() 15 | { 16 | Application.EnableVisualStyles(); 17 | Application.SetCompatibleTextRenderingDefault(false); 18 | Application.Run(new frmCreateTCPClient()); 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /TCPClient/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("TCPClient")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("TCPClient")] 13 | [assembly: AssemblyCopyright("Copyright © 2015")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("820dbeb7-0558-4f37-b0d1-fa7e135ef3f2")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /TCPClient/Properties/Resources.Designer.cs: -------------------------------------------------------------------------------- 1 | //------------------------------------------------------------------------------ 2 | // 3 | // This code was generated by a tool. 4 | // Runtime Version:4.0.30319.18444 5 | // 6 | // Changes to this file may cause incorrect behavior and will be lost if 7 | // the code is regenerated. 8 | // 9 | //------------------------------------------------------------------------------ 10 | 11 | namespace TCPClient.Properties 12 | { 13 | 14 | 15 | /// 16 | /// A strongly-typed resource class, for looking up localized strings, etc. 17 | /// 18 | // This class was auto-generated by the StronglyTypedResourceBuilder 19 | // class via a tool like ResGen or Visual Studio. 20 | // To add or remove a member, edit your .ResX file then rerun ResGen 21 | // with the /str option, or rebuild your VS project. 22 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] 23 | [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] 24 | [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] 25 | internal class Resources 26 | { 27 | 28 | private static global::System.Resources.ResourceManager resourceMan; 29 | 30 | private static global::System.Globalization.CultureInfo resourceCulture; 31 | 32 | [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] 33 | internal Resources() 34 | { 35 | } 36 | 37 | /// 38 | /// Returns the cached ResourceManager instance used by this class. 39 | /// 40 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] 41 | internal static global::System.Resources.ResourceManager ResourceManager 42 | { 43 | get 44 | { 45 | if ((resourceMan == null)) 46 | { 47 | global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("TCPClient.Properties.Resources", typeof(Resources).Assembly); 48 | resourceMan = temp; 49 | } 50 | return resourceMan; 51 | } 52 | } 53 | 54 | /// 55 | /// Overrides the current thread's CurrentUICulture property for all 56 | /// resource lookups using this strongly typed resource class. 57 | /// 58 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] 59 | internal static global::System.Globalization.CultureInfo Culture 60 | { 61 | get 62 | { 63 | return resourceCulture; 64 | } 65 | set 66 | { 67 | resourceCulture = value; 68 | } 69 | } 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /TCPClient/Properties/Resources.resx: -------------------------------------------------------------------------------- 1 |  2 | 3 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | text/microsoft-resx 107 | 108 | 109 | 2.0 110 | 111 | 112 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 113 | 114 | 115 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 116 | 117 | -------------------------------------------------------------------------------- /TCPClient/Properties/Settings.Designer.cs: -------------------------------------------------------------------------------- 1 | //------------------------------------------------------------------------------ 2 | // 3 | // This code was generated by a tool. 4 | // Runtime Version:4.0.30319.18444 5 | // 6 | // Changes to this file may cause incorrect behavior and will be lost if 7 | // the code is regenerated. 8 | // 9 | //------------------------------------------------------------------------------ 10 | 11 | namespace TCPClient.Properties 12 | { 13 | 14 | 15 | [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] 16 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "10.0.0.0")] 17 | internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase 18 | { 19 | 20 | private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); 21 | 22 | public static Settings Default 23 | { 24 | get 25 | { 26 | return defaultInstance; 27 | } 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /TCPClient/Properties/Settings.settings: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /TCPClient/TCPClient.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Debug 5 | x86 6 | 8.0.30703 7 | 2.0 8 | {2E4F81C6-21C2-4326-9684-0470B027FCA7} 9 | WinExe 10 | Properties 11 | TCPClient 12 | TCPClient 13 | v4.0 14 | Client 15 | 512 16 | 17 | 18 | x86 19 | true 20 | full 21 | false 22 | bin\Debug\ 23 | DEBUG;TRACE 24 | prompt 25 | 4 26 | 27 | 28 | x86 29 | pdbonly 30 | true 31 | bin\Release\ 32 | TRACE 33 | prompt 34 | 4 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | Form 51 | 52 | 53 | frmCreateTCPClient.cs 54 | 55 | 56 | 57 | 58 | Form 59 | 60 | 61 | frmTCPClient.cs 62 | 63 | 64 | frmCreateTCPClient.cs 65 | 66 | 67 | ResXFileCodeGenerator 68 | Resources.Designer.cs 69 | Designer 70 | 71 | 72 | True 73 | Resources.resx 74 | 75 | 76 | frmTCPClient.cs 77 | 78 | 79 | SettingsSingleFileGenerator 80 | Settings.Designer.cs 81 | 82 | 83 | True 84 | Settings.settings 85 | True 86 | 87 | 88 | 89 | 90 | {F2B5C19C-218D-48E0-9BA1-32673F1352B7} 91 | TJSYXY.Communication 92 | 93 | 94 | 95 | 102 | -------------------------------------------------------------------------------- /TCPClient/frmCreateTCPClient.Designer.cs: -------------------------------------------------------------------------------- 1 | namespace TCPClient 2 | { 3 | partial class frmCreateTCPClient 4 | { 5 | /// 6 | /// Required designer variable. 7 | /// 8 | private System.ComponentModel.IContainer components = null; 9 | 10 | /// 11 | /// Clean up any resources being used. 12 | /// 13 | /// true if managed resources should be disposed; otherwise, false. 14 | protected override void Dispose(bool disposing) 15 | { 16 | if (disposing && (components != null)) 17 | { 18 | components.Dispose(); 19 | } 20 | base.Dispose(disposing); 21 | } 22 | 23 | #region Windows Form Designer generated code 24 | 25 | /// 26 | /// Required method for Designer support - do not modify 27 | /// the contents of this method with the code editor. 28 | /// 29 | private void InitializeComponent() 30 | { 31 | this.textBox2 = new System.Windows.Forms.TextBox(); 32 | this.label2 = new System.Windows.Forms.Label(); 33 | this.textBox1 = new System.Windows.Forms.TextBox(); 34 | this.label1 = new System.Windows.Forms.Label(); 35 | this.textBox3 = new System.Windows.Forms.TextBox(); 36 | this.label3 = new System.Windows.Forms.Label(); 37 | this.button1 = new System.Windows.Forms.Button(); 38 | this.SuspendLayout(); 39 | // 40 | // textBox2 41 | // 42 | this.textBox2.Location = new System.Drawing.Point(32, 77); 43 | this.textBox2.Name = "textBox2"; 44 | this.textBox2.Size = new System.Drawing.Size(176, 21); 45 | this.textBox2.TabIndex = 8; 46 | // 47 | // label2 48 | // 49 | this.label2.AutoSize = true; 50 | this.label2.Location = new System.Drawing.Point(31, 62); 51 | this.label2.Name = "label2"; 52 | this.label2.Size = new System.Drawing.Size(65, 12); 53 | this.label2.TabIndex = 7; 54 | this.label2.Text = "服务器端口"; 55 | // 56 | // textBox1 57 | // 58 | this.textBox1.Location = new System.Drawing.Point(31, 32); 59 | this.textBox1.Name = "textBox1"; 60 | this.textBox1.Size = new System.Drawing.Size(176, 21); 61 | this.textBox1.TabIndex = 6; 62 | // 63 | // label1 64 | // 65 | this.label1.AutoSize = true; 66 | this.label1.Location = new System.Drawing.Point(30, 17); 67 | this.label1.Name = "label1"; 68 | this.label1.Size = new System.Drawing.Size(53, 12); 69 | this.label1.TabIndex = 5; 70 | this.label1.Text = "服务器IP"; 71 | // 72 | // textBox3 73 | // 74 | this.textBox3.Location = new System.Drawing.Point(33, 123); 75 | this.textBox3.Name = "textBox3"; 76 | this.textBox3.Size = new System.Drawing.Size(176, 21); 77 | this.textBox3.TabIndex = 10; 78 | // 79 | // label3 80 | // 81 | this.label3.AutoSize = true; 82 | this.label3.Location = new System.Drawing.Point(32, 108); 83 | this.label3.Name = "label3"; 84 | this.label3.Size = new System.Drawing.Size(83, 12); 85 | this.label3.TabIndex = 9; 86 | this.label3.Text = "TCP客户端名称"; 87 | // 88 | // button1 89 | // 90 | this.button1.Location = new System.Drawing.Point(133, 172); 91 | this.button1.Name = "button1"; 92 | this.button1.Size = new System.Drawing.Size(75, 23); 93 | this.button1.TabIndex = 11; 94 | this.button1.Text = "创建"; 95 | this.button1.UseVisualStyleBackColor = true; 96 | this.button1.Click += new System.EventHandler(this.button1_Click); 97 | // 98 | // frmCreateTCPClient 99 | // 100 | this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); 101 | this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; 102 | this.ClientSize = new System.Drawing.Size(251, 222); 103 | this.ControlBox = false; 104 | this.Controls.Add(this.button1); 105 | this.Controls.Add(this.textBox3); 106 | this.Controls.Add(this.label3); 107 | this.Controls.Add(this.textBox2); 108 | this.Controls.Add(this.label2); 109 | this.Controls.Add(this.textBox1); 110 | this.Controls.Add(this.label1); 111 | this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow; 112 | this.Name = "frmCreateTCPClient"; 113 | this.Text = "CreateTCPClient"; 114 | this.ResumeLayout(false); 115 | this.PerformLayout(); 116 | 117 | } 118 | 119 | #endregion 120 | 121 | private System.Windows.Forms.TextBox textBox2; 122 | private System.Windows.Forms.Label label2; 123 | private System.Windows.Forms.TextBox textBox1; 124 | private System.Windows.Forms.Label label1; 125 | private System.Windows.Forms.TextBox textBox3; 126 | private System.Windows.Forms.Label label3; 127 | private System.Windows.Forms.Button button1; 128 | } 129 | } 130 | 131 | -------------------------------------------------------------------------------- /TCPClient/frmCreateTCPClient.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.ComponentModel; 4 | using System.Data; 5 | using System.Drawing; 6 | using System.Linq; 7 | using System.Text; 8 | using System.Windows.Forms; 9 | using TJSYXY.Communication; 10 | using TJSYXY.Communication.TCP; 11 | 12 | namespace TCPClient 13 | { 14 | public partial class frmCreateTCPClient : Form 15 | { 16 | public frmCreateTCPClient() 17 | { 18 | InitializeComponent(); 19 | } 20 | /// 21 | /// 创建客户端 22 | /// 23 | /// 24 | /// 25 | private void button1_Click(object sender, EventArgs e) 26 | { 27 | if (TCPClientManager.ClientExist(textBox3.Text)) 28 | { 29 | MessageBox.Show("客户端已存在!"); 30 | return; 31 | } 32 | 33 | TCPClientManager manager = new TCPClientManager(textBox3.Text); //创建客户端 34 | manager.Connect(textBox1.Text, int.Parse(textBox2.Text)); 35 | 36 | frmTCPClient frmtcpclient = new frmTCPClient(textBox3.Text); 37 | frmtcpclient.Show(); 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /TCPClient/frmCreateTCPClient.resx: -------------------------------------------------------------------------------- 1 |  2 | 3 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | text/microsoft-resx 110 | 111 | 112 | 2.0 113 | 114 | 115 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 116 | 117 | 118 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 119 | 120 | -------------------------------------------------------------------------------- /TCPClient/frmTCPClient.Designer.cs: -------------------------------------------------------------------------------- 1 | namespace TCPClient 2 | { 3 | partial class frmTCPClient 4 | { 5 | /// 6 | /// Required designer variable. 7 | /// 8 | private System.ComponentModel.IContainer components = null; 9 | 10 | /// 11 | /// Clean up any resources being used. 12 | /// 13 | /// true if managed resources should be disposed; otherwise, false. 14 | protected override void Dispose(bool disposing) 15 | { 16 | if (disposing && (components != null)) 17 | { 18 | components.Dispose(); 19 | } 20 | base.Dispose(disposing); 21 | } 22 | 23 | #region Windows Form Designer generated code 24 | 25 | /// 26 | /// Required method for Designer support - do not modify 27 | /// the contents of this method with the code editor. 28 | /// 29 | private void InitializeComponent() 30 | { 31 | this.button1 = new System.Windows.Forms.Button(); 32 | this.groupBox1 = new System.Windows.Forms.GroupBox(); 33 | this.button3 = new System.Windows.Forms.Button(); 34 | this.textBox3 = new System.Windows.Forms.TextBox(); 35 | this.button2 = new System.Windows.Forms.Button(); 36 | this.textBox2 = new System.Windows.Forms.TextBox(); 37 | this.pictureBox1 = new System.Windows.Forms.PictureBox(); 38 | this.textBox1 = new System.Windows.Forms.TextBox(); 39 | this.groupBox1.SuspendLayout(); 40 | ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit(); 41 | this.SuspendLayout(); 42 | // 43 | // button1 44 | // 45 | this.button1.Location = new System.Drawing.Point(391, 306); 46 | this.button1.Name = "button1"; 47 | this.button1.Size = new System.Drawing.Size(75, 23); 48 | this.button1.TabIndex = 8; 49 | this.button1.Text = "关闭"; 50 | this.button1.UseVisualStyleBackColor = true; 51 | this.button1.Click += new System.EventHandler(this.button1_Click); 52 | // 53 | // groupBox1 54 | // 55 | this.groupBox1.Controls.Add(this.button3); 56 | this.groupBox1.Controls.Add(this.textBox3); 57 | this.groupBox1.Controls.Add(this.button2); 58 | this.groupBox1.Controls.Add(this.textBox2); 59 | this.groupBox1.Location = new System.Drawing.Point(12, 200); 60 | this.groupBox1.Name = "groupBox1"; 61 | this.groupBox1.Size = new System.Drawing.Size(454, 100); 62 | this.groupBox1.TabIndex = 7; 63 | this.groupBox1.TabStop = false; 64 | this.groupBox1.Text = "发送数据"; 65 | // 66 | // button3 67 | // 68 | this.button3.Location = new System.Drawing.Point(349, 48); 69 | this.button3.Name = "button3"; 70 | this.button3.Size = new System.Drawing.Size(89, 23); 71 | this.button3.TabIndex = 6; 72 | this.button3.Text = "发送图片"; 73 | this.button3.UseVisualStyleBackColor = true; 74 | this.button3.Click += new System.EventHandler(this.button3_Click); 75 | // 76 | // textBox3 77 | // 78 | this.textBox3.Location = new System.Drawing.Point(11, 47); 79 | this.textBox3.Name = "textBox3"; 80 | this.textBox3.ReadOnly = true; 81 | this.textBox3.Size = new System.Drawing.Size(332, 21); 82 | this.textBox3.TabIndex = 5; 83 | // 84 | // button2 85 | // 86 | this.button2.Location = new System.Drawing.Point(349, 19); 87 | this.button2.Name = "button2"; 88 | this.button2.Size = new System.Drawing.Size(89, 23); 89 | this.button2.TabIndex = 1; 90 | this.button2.Text = "发送文本"; 91 | this.button2.UseVisualStyleBackColor = true; 92 | this.button2.Click += new System.EventHandler(this.button2_Click); 93 | // 94 | // textBox2 95 | // 96 | this.textBox2.Location = new System.Drawing.Point(11, 20); 97 | this.textBox2.Name = "textBox2"; 98 | this.textBox2.Size = new System.Drawing.Size(332, 21); 99 | this.textBox2.TabIndex = 0; 100 | // 101 | // pictureBox1 102 | // 103 | this.pictureBox1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; 104 | this.pictureBox1.Location = new System.Drawing.Point(294, 12); 105 | this.pictureBox1.Name = "pictureBox1"; 106 | this.pictureBox1.Size = new System.Drawing.Size(172, 176); 107 | this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom; 108 | this.pictureBox1.TabIndex = 6; 109 | this.pictureBox1.TabStop = false; 110 | // 111 | // textBox1 112 | // 113 | this.textBox1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; 114 | this.textBox1.Location = new System.Drawing.Point(12, 12); 115 | this.textBox1.Multiline = true; 116 | this.textBox1.Name = "textBox1"; 117 | this.textBox1.ReadOnly = true; 118 | this.textBox1.Size = new System.Drawing.Size(276, 176); 119 | this.textBox1.TabIndex = 5; 120 | // 121 | // frmTCPClient 122 | // 123 | this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); 124 | this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; 125 | this.ClientSize = new System.Drawing.Size(480, 346); 126 | this.Controls.Add(this.button1); 127 | this.Controls.Add(this.groupBox1); 128 | this.Controls.Add(this.pictureBox1); 129 | this.Controls.Add(this.textBox1); 130 | this.Name = "frmTCPClient"; 131 | this.Text = "TCPClient"; 132 | this.Load += new System.EventHandler(this.frmTCPClient_Load); 133 | this.groupBox1.ResumeLayout(false); 134 | this.groupBox1.PerformLayout(); 135 | ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit(); 136 | this.ResumeLayout(false); 137 | this.PerformLayout(); 138 | 139 | } 140 | 141 | #endregion 142 | 143 | private System.Windows.Forms.Button button1; 144 | private System.Windows.Forms.GroupBox groupBox1; 145 | private System.Windows.Forms.Button button3; 146 | private System.Windows.Forms.TextBox textBox3; 147 | private System.Windows.Forms.Button button2; 148 | private System.Windows.Forms.TextBox textBox2; 149 | private System.Windows.Forms.PictureBox pictureBox1; 150 | private System.Windows.Forms.TextBox textBox1; 151 | } 152 | } -------------------------------------------------------------------------------- /TCPClient/frmTCPClient.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.ComponentModel; 4 | using System.Data; 5 | using System.Drawing; 6 | using System.Linq; 7 | using System.Text; 8 | using System.Windows.Forms; 9 | using TJSYXY.Communication.TCP; 10 | using TJSYXY.Communication; 11 | using System.IO; 12 | using System.Drawing.Imaging; 13 | 14 | namespace TCPClient 15 | { 16 | public partial class frmTCPClient : Form 17 | { 18 | private string _client_id; 19 | 20 | public frmTCPClient() 21 | { 22 | InitializeComponent(); 23 | } 24 | public frmTCPClient(string client_id) 25 | : this() 26 | { 27 | _client_id = client_id; 28 | } 29 | /// 30 | /// 窗体加载 31 | /// 32 | /// 33 | /// 34 | private void frmTCPClient_Load(object sender, EventArgs e) 35 | { 36 | Text = "TCPClient " + _client_id; 37 | 38 | //注册事件 39 | TCPClientManager manager = new TCPClientManager(_client_id); //访问客户端 40 | manager.TCPMessageReceived += new TCPMessageReceivedEventHandler(manager_TCPMessageReceived); 41 | manager.TCPClientDisConnected4Pulse += new TCPClientDisConnected4PulseEventHandler(manager_TCPClientDisConnected4Pulse); 42 | manager.TCPClientDisConnected += new TCPClientDisConnectedEventHandler(manager_TCPClientDisConnected); 43 | } 44 | 45 | #region 46 | /// 47 | /// 断线 48 | /// 49 | /// 50 | /// 51 | void manager_TCPClientDisConnected(string csID, TCPClientDisConnectedEventArgs args) 52 | { 53 | this.Invoke((Action)delegate() 54 | { 55 | textBox1.AppendText(args.Time.ToLongTimeString() + " 与服务器断开连接\n"); 56 | }); 57 | } 58 | /// 59 | /// 心跳包发送失败 60 | /// 61 | /// 62 | /// 63 | void manager_TCPClientDisConnected4Pulse(string csID, int uid) 64 | { 65 | this.Invoke((Action)delegate() 66 | { 67 | textBox1.AppendText("发送心跳包失败\n"); 68 | }); 69 | } 70 | /// 71 | /// 收到消息 72 | /// 73 | /// 74 | /// 75 | void manager_TCPMessageReceived(string csID, TCPMessageReceivedEventArgs args) 76 | { 77 | this.Invoke((Action)delegate() 78 | { 79 | if (args.Msg == Msg.Zmsg1) //文本 80 | { 81 | textBox1.AppendText(args.Time.ToLongTimeString() + " " + args.End.RemoteIP + ":" + args.End.RemotePort + " 发送文本:\n" 82 | + Encoding.Unicode.GetString(args.Data) + "\n"); 83 | } 84 | if (args.Msg == Msg.Zmsg2) //图片 85 | { 86 | textBox1.AppendText(args.Time.ToLongTimeString() + " " + args.End.RemoteIP + ":" + args.End.RemotePort + " 发送图片:\n" 87 | + "见右方-->\n"); 88 | Image image = Image.FromStream(new MemoryStream(args.Data)); 89 | pictureBox1.Image = image; 90 | } 91 | }); 92 | } 93 | #endregion 94 | 95 | /// 96 | /// 发送文本 97 | /// 98 | /// 99 | /// 100 | private void button2_Click(object sender, EventArgs e) 101 | { 102 | TCPClientManager manager = new TCPClientManager(_client_id); 103 | manager.Send(Msg.Zmsg1, Encoding.Unicode.GetBytes(textBox2.Text)); //同步发送文本 104 | } 105 | /// 106 | /// 发送图片 107 | /// 108 | /// 109 | /// 110 | private void button3_Click(object sender, EventArgs e) 111 | { 112 | using (OpenFileDialog ofd = new OpenFileDialog()) 113 | { 114 | ofd.Filter = "图片文件|*.jpg;*jpeg"; 115 | if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK) 116 | { 117 | textBox3.Text = ofd.FileName; 118 | Image image = Image.FromFile(textBox3.Text); 119 | using (MemoryStream ms = new MemoryStream()) 120 | { 121 | image.Save(ms, ImageFormat.Jpeg); 122 | 123 | TCPClientManager manager = new TCPClientManager(_client_id); 124 | manager.SendAsync(Msg.Zmsg2, ms.ToArray(), null); //异步发送图片 125 | } 126 | } 127 | } 128 | } 129 | /// 130 | /// 关闭 131 | /// 132 | /// 133 | /// 134 | private void button1_Click(object sender, EventArgs e) 135 | { 136 | TCPClientManager manager = new TCPClientManager(_client_id); 137 | manager.DisConnect(); 138 | Close(); 139 | } 140 | } 141 | } 142 | -------------------------------------------------------------------------------- /TCPClient/frmTCPClient.resx: -------------------------------------------------------------------------------- 1 |  2 | 3 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | text/microsoft-resx 110 | 111 | 112 | 2.0 113 | 114 | 115 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 116 | 117 | 118 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 119 | 120 | -------------------------------------------------------------------------------- /TCPServer/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Windows.Forms; 5 | 6 | namespace TCPServer 7 | { 8 | static class Program 9 | { 10 | /// 11 | /// The main entry point for the application. 12 | /// 13 | [STAThread] 14 | static void Main() 15 | { 16 | Application.EnableVisualStyles(); 17 | Application.SetCompatibleTextRenderingDefault(false); 18 | Application.Run(new frmCreateTCPServer()); 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /TCPServer/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("TCPServer")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("TCPServer")] 13 | [assembly: AssemblyCopyright("Copyright © 2015")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("0a74621d-a0aa-4f7b-b40f-11df5ee845bb")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /TCPServer/Properties/Resources.Designer.cs: -------------------------------------------------------------------------------- 1 | //------------------------------------------------------------------------------ 2 | // 3 | // This code was generated by a tool. 4 | // Runtime Version:4.0.30319.18444 5 | // 6 | // Changes to this file may cause incorrect behavior and will be lost if 7 | // the code is regenerated. 8 | // 9 | //------------------------------------------------------------------------------ 10 | 11 | namespace TCPServer.Properties 12 | { 13 | 14 | 15 | /// 16 | /// A strongly-typed resource class, for looking up localized strings, etc. 17 | /// 18 | // This class was auto-generated by the StronglyTypedResourceBuilder 19 | // class via a tool like ResGen or Visual Studio. 20 | // To add or remove a member, edit your .ResX file then rerun ResGen 21 | // with the /str option, or rebuild your VS project. 22 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] 23 | [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] 24 | [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] 25 | internal class Resources 26 | { 27 | 28 | private static global::System.Resources.ResourceManager resourceMan; 29 | 30 | private static global::System.Globalization.CultureInfo resourceCulture; 31 | 32 | [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] 33 | internal Resources() 34 | { 35 | } 36 | 37 | /// 38 | /// Returns the cached ResourceManager instance used by this class. 39 | /// 40 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] 41 | internal static global::System.Resources.ResourceManager ResourceManager 42 | { 43 | get 44 | { 45 | if ((resourceMan == null)) 46 | { 47 | global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("TCPServer.Properties.Resources", typeof(Resources).Assembly); 48 | resourceMan = temp; 49 | } 50 | return resourceMan; 51 | } 52 | } 53 | 54 | /// 55 | /// Overrides the current thread's CurrentUICulture property for all 56 | /// resource lookups using this strongly typed resource class. 57 | /// 58 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] 59 | internal static global::System.Globalization.CultureInfo Culture 60 | { 61 | get 62 | { 63 | return resourceCulture; 64 | } 65 | set 66 | { 67 | resourceCulture = value; 68 | } 69 | } 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /TCPServer/Properties/Resources.resx: -------------------------------------------------------------------------------- 1 |  2 | 3 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | text/microsoft-resx 107 | 108 | 109 | 2.0 110 | 111 | 112 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 113 | 114 | 115 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 116 | 117 | -------------------------------------------------------------------------------- /TCPServer/Properties/Settings.Designer.cs: -------------------------------------------------------------------------------- 1 | //------------------------------------------------------------------------------ 2 | // 3 | // This code was generated by a tool. 4 | // Runtime Version:4.0.30319.18444 5 | // 6 | // Changes to this file may cause incorrect behavior and will be lost if 7 | // the code is regenerated. 8 | // 9 | //------------------------------------------------------------------------------ 10 | 11 | namespace TCPServer.Properties 12 | { 13 | 14 | 15 | [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] 16 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "10.0.0.0")] 17 | internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase 18 | { 19 | 20 | private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); 21 | 22 | public static Settings Default 23 | { 24 | get 25 | { 26 | return defaultInstance; 27 | } 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /TCPServer/Properties/Settings.settings: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /TCPServer/TCPServer.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Debug 5 | x86 6 | 8.0.30703 7 | 2.0 8 | {75FA619B-F5AA-4328-BC8B-759B8A12F77C} 9 | WinExe 10 | Properties 11 | TCPServer 12 | TCPServer 13 | v4.0 14 | Client 15 | 512 16 | 17 | 18 | x86 19 | true 20 | full 21 | false 22 | bin\Debug\ 23 | DEBUG;TRACE 24 | prompt 25 | 4 26 | 27 | 28 | x86 29 | pdbonly 30 | true 31 | bin\Release\ 32 | TRACE 33 | prompt 34 | 4 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | Form 51 | 52 | 53 | frmCreateTCPServer.cs 54 | 55 | 56 | Form 57 | 58 | 59 | frmTCPServer.cs 60 | 61 | 62 | 63 | 64 | frmCreateTCPServer.cs 65 | 66 | 67 | frmTCPServer.cs 68 | 69 | 70 | ResXFileCodeGenerator 71 | Resources.Designer.cs 72 | Designer 73 | 74 | 75 | True 76 | Resources.resx 77 | 78 | 79 | SettingsSingleFileGenerator 80 | Settings.Designer.cs 81 | 82 | 83 | True 84 | Settings.settings 85 | True 86 | 87 | 88 | 89 | 90 | {F2B5C19C-218D-48E0-9BA1-32673F1352B7} 91 | TJSYXY.Communication 92 | 93 | 94 | 95 | 102 | -------------------------------------------------------------------------------- /TCPServer/frmCreateTCPServer.Designer.cs: -------------------------------------------------------------------------------- 1 | namespace TCPServer 2 | { 3 | partial class frmCreateTCPServer 4 | { 5 | /// 6 | /// Required designer variable. 7 | /// 8 | private System.ComponentModel.IContainer components = null; 9 | 10 | /// 11 | /// Clean up any resources being used. 12 | /// 13 | /// true if managed resources should be disposed; otherwise, false. 14 | protected override void Dispose(bool disposing) 15 | { 16 | if (disposing && (components != null)) 17 | { 18 | components.Dispose(); 19 | } 20 | base.Dispose(disposing); 21 | } 22 | 23 | #region Windows Form Designer generated code 24 | 25 | /// 26 | /// Required method for Designer support - do not modify 27 | /// the contents of this method with the code editor. 28 | /// 29 | private void InitializeComponent() 30 | { 31 | this.label1 = new System.Windows.Forms.Label(); 32 | this.textBox1 = new System.Windows.Forms.TextBox(); 33 | this.button1 = new System.Windows.Forms.Button(); 34 | this.textBox2 = new System.Windows.Forms.TextBox(); 35 | this.label2 = new System.Windows.Forms.Label(); 36 | this.SuspendLayout(); 37 | // 38 | // label1 39 | // 40 | this.label1.AutoSize = true; 41 | this.label1.Location = new System.Drawing.Point(29, 25); 42 | this.label1.Name = "label1"; 43 | this.label1.Size = new System.Drawing.Size(65, 12); 44 | this.label1.TabIndex = 0; 45 | this.label1.Text = "侦听端口号"; 46 | // 47 | // textBox1 48 | // 49 | this.textBox1.Location = new System.Drawing.Point(30, 40); 50 | this.textBox1.Name = "textBox1"; 51 | this.textBox1.Size = new System.Drawing.Size(176, 21); 52 | this.textBox1.TabIndex = 1; 53 | // 54 | // button1 55 | // 56 | this.button1.Location = new System.Drawing.Point(131, 122); 57 | this.button1.Name = "button1"; 58 | this.button1.Size = new System.Drawing.Size(75, 23); 59 | this.button1.TabIndex = 2; 60 | this.button1.Text = "创建"; 61 | this.button1.UseVisualStyleBackColor = true; 62 | this.button1.Click += new System.EventHandler(this.button1_Click); 63 | // 64 | // textBox2 65 | // 66 | this.textBox2.Location = new System.Drawing.Point(31, 85); 67 | this.textBox2.Name = "textBox2"; 68 | this.textBox2.Size = new System.Drawing.Size(176, 21); 69 | this.textBox2.TabIndex = 4; 70 | // 71 | // label2 72 | // 73 | this.label2.AutoSize = true; 74 | this.label2.Location = new System.Drawing.Point(30, 70); 75 | this.label2.Name = "label2"; 76 | this.label2.Size = new System.Drawing.Size(83, 12); 77 | this.label2.TabIndex = 3; 78 | this.label2.Text = "TCP服务器名称"; 79 | // 80 | // frmCreateTCPServer 81 | // 82 | this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); 83 | this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; 84 | this.ClientSize = new System.Drawing.Size(239, 157); 85 | this.ControlBox = false; 86 | this.Controls.Add(this.textBox2); 87 | this.Controls.Add(this.label2); 88 | this.Controls.Add(this.button1); 89 | this.Controls.Add(this.textBox1); 90 | this.Controls.Add(this.label1); 91 | this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow; 92 | this.Name = "frmCreateTCPServer"; 93 | this.Text = "CreateTCPServer"; 94 | this.ResumeLayout(false); 95 | this.PerformLayout(); 96 | 97 | } 98 | 99 | #endregion 100 | 101 | private System.Windows.Forms.Label label1; 102 | private System.Windows.Forms.TextBox textBox1; 103 | private System.Windows.Forms.Button button1; 104 | private System.Windows.Forms.TextBox textBox2; 105 | private System.Windows.Forms.Label label2; 106 | } 107 | } -------------------------------------------------------------------------------- /TCPServer/frmCreateTCPServer.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.ComponentModel; 4 | using System.Data; 5 | using System.Drawing; 6 | using System.Linq; 7 | using System.Text; 8 | using System.Windows.Forms; 9 | using TJSYXY.Communication; 10 | using TJSYXY.Communication.TCP; 11 | 12 | namespace TCPServer 13 | { 14 | public partial class frmCreateTCPServer : Form 15 | { 16 | public frmCreateTCPServer() 17 | { 18 | InitializeComponent(); 19 | } 20 | 21 | private void button1_Click(object sender, EventArgs e) 22 | { 23 | if (TCPServerManager.ServerExist(textBox2.Text)) 24 | { 25 | MessageBox.Show("服务器已存在!"); 26 | return; 27 | } 28 | 29 | TCPServerManager manager = new TCPServerManager(textBox2.Text); //创建服务器 30 | manager.Start(int.Parse(textBox1.Text)); //启动服务器 31 | 32 | frmTCPServer frmtcpserver = new frmTCPServer(textBox2.Text, int.Parse(textBox1.Text)); 33 | frmtcpserver.Show(); 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /TCPServer/frmCreateTCPServer.resx: -------------------------------------------------------------------------------- 1 |  2 | 3 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | text/microsoft-resx 110 | 111 | 112 | 2.0 113 | 114 | 115 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 116 | 117 | 118 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 119 | 120 | -------------------------------------------------------------------------------- /TCPServer/frmTCPServer.Designer.cs: -------------------------------------------------------------------------------- 1 | namespace TCPServer 2 | { 3 | partial class frmTCPServer 4 | { 5 | /// 6 | /// Required designer variable. 7 | /// 8 | private System.ComponentModel.IContainer components = null; 9 | 10 | /// 11 | /// Clean up any resources being used. 12 | /// 13 | /// true if managed resources should be disposed; otherwise, false. 14 | protected override void Dispose(bool disposing) 15 | { 16 | if (disposing && (components != null)) 17 | { 18 | components.Dispose(); 19 | } 20 | base.Dispose(disposing); 21 | } 22 | 23 | #region Windows Form Designer generated code 24 | 25 | /// 26 | /// Required method for Designer support - do not modify 27 | /// the contents of this method with the code editor. 28 | /// 29 | private void InitializeComponent() 30 | { 31 | this.dataGridView1 = new System.Windows.Forms.DataGridView(); 32 | this.Column1 = new System.Windows.Forms.DataGridViewTextBoxColumn(); 33 | this.Column2 = new System.Windows.Forms.DataGridViewTextBoxColumn(); 34 | this.Column3 = new System.Windows.Forms.DataGridViewTextBoxColumn(); 35 | this.Column4 = new System.Windows.Forms.DataGridViewTextBoxColumn(); 36 | this.textBox1 = new System.Windows.Forms.TextBox(); 37 | this.pictureBox1 = new System.Windows.Forms.PictureBox(); 38 | this.groupBox1 = new System.Windows.Forms.GroupBox(); 39 | this.button3 = new System.Windows.Forms.Button(); 40 | this.textBox3 = new System.Windows.Forms.TextBox(); 41 | this.button2 = new System.Windows.Forms.Button(); 42 | this.textBox2 = new System.Windows.Forms.TextBox(); 43 | this.button1 = new System.Windows.Forms.Button(); 44 | ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit(); 45 | ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit(); 46 | this.groupBox1.SuspendLayout(); 47 | this.SuspendLayout(); 48 | // 49 | // dataGridView1 50 | // 51 | this.dataGridView1.AllowUserToAddRows = false; 52 | this.dataGridView1.AllowUserToDeleteRows = false; 53 | this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; 54 | this.dataGridView1.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { 55 | this.Column1, 56 | this.Column2, 57 | this.Column3, 58 | this.Column4}); 59 | this.dataGridView1.Location = new System.Drawing.Point(12, 12); 60 | this.dataGridView1.Name = "dataGridView1"; 61 | this.dataGridView1.ReadOnly = true; 62 | this.dataGridView1.RowTemplate.Height = 23; 63 | this.dataGridView1.Size = new System.Drawing.Size(454, 117); 64 | this.dataGridView1.TabIndex = 0; 65 | // 66 | // Column1 67 | // 68 | this.Column1.HeaderText = "终端UID"; 69 | this.Column1.Name = "Column1"; 70 | this.Column1.ReadOnly = true; 71 | // 72 | // Column2 73 | // 74 | this.Column2.HeaderText = "远程IP"; 75 | this.Column2.Name = "Column2"; 76 | this.Column2.ReadOnly = true; 77 | // 78 | // Column3 79 | // 80 | this.Column3.HeaderText = "远程端口"; 81 | this.Column3.Name = "Column3"; 82 | this.Column3.ReadOnly = true; 83 | // 84 | // Column4 85 | // 86 | this.Column4.HeaderText = "登录时间"; 87 | this.Column4.Name = "Column4"; 88 | this.Column4.ReadOnly = true; 89 | // 90 | // textBox1 91 | // 92 | this.textBox1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; 93 | this.textBox1.Location = new System.Drawing.Point(12, 135); 94 | this.textBox1.Multiline = true; 95 | this.textBox1.Name = "textBox1"; 96 | this.textBox1.ReadOnly = true; 97 | this.textBox1.Size = new System.Drawing.Size(276, 176); 98 | this.textBox1.TabIndex = 1; 99 | // 100 | // pictureBox1 101 | // 102 | this.pictureBox1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; 103 | this.pictureBox1.Location = new System.Drawing.Point(294, 135); 104 | this.pictureBox1.Name = "pictureBox1"; 105 | this.pictureBox1.Size = new System.Drawing.Size(172, 176); 106 | this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom; 107 | this.pictureBox1.TabIndex = 2; 108 | this.pictureBox1.TabStop = false; 109 | // 110 | // groupBox1 111 | // 112 | this.groupBox1.Controls.Add(this.button3); 113 | this.groupBox1.Controls.Add(this.textBox3); 114 | this.groupBox1.Controls.Add(this.button2); 115 | this.groupBox1.Controls.Add(this.textBox2); 116 | this.groupBox1.Location = new System.Drawing.Point(12, 323); 117 | this.groupBox1.Name = "groupBox1"; 118 | this.groupBox1.Size = new System.Drawing.Size(454, 100); 119 | this.groupBox1.TabIndex = 3; 120 | this.groupBox1.TabStop = false; 121 | this.groupBox1.Text = "发送数据"; 122 | // 123 | // button3 124 | // 125 | this.button3.Location = new System.Drawing.Point(349, 48); 126 | this.button3.Name = "button3"; 127 | this.button3.Size = new System.Drawing.Size(89, 23); 128 | this.button3.TabIndex = 6; 129 | this.button3.Text = "发送图片"; 130 | this.button3.UseVisualStyleBackColor = true; 131 | this.button3.Click += new System.EventHandler(this.button3_Click); 132 | // 133 | // textBox3 134 | // 135 | this.textBox3.Location = new System.Drawing.Point(11, 47); 136 | this.textBox3.Name = "textBox3"; 137 | this.textBox3.ReadOnly = true; 138 | this.textBox3.Size = new System.Drawing.Size(332, 21); 139 | this.textBox3.TabIndex = 5; 140 | // 141 | // button2 142 | // 143 | this.button2.Location = new System.Drawing.Point(349, 19); 144 | this.button2.Name = "button2"; 145 | this.button2.Size = new System.Drawing.Size(89, 23); 146 | this.button2.TabIndex = 1; 147 | this.button2.Text = "发送文本"; 148 | this.button2.UseVisualStyleBackColor = true; 149 | this.button2.Click += new System.EventHandler(this.button2_Click); 150 | // 151 | // textBox2 152 | // 153 | this.textBox2.Location = new System.Drawing.Point(11, 20); 154 | this.textBox2.Name = "textBox2"; 155 | this.textBox2.Size = new System.Drawing.Size(332, 21); 156 | this.textBox2.TabIndex = 0; 157 | // 158 | // button1 159 | // 160 | this.button1.Location = new System.Drawing.Point(391, 429); 161 | this.button1.Name = "button1"; 162 | this.button1.Size = new System.Drawing.Size(75, 23); 163 | this.button1.TabIndex = 4; 164 | this.button1.Text = "关闭"; 165 | this.button1.UseVisualStyleBackColor = true; 166 | this.button1.Click += new System.EventHandler(this.button1_Click); 167 | // 168 | // frmTCPServer 169 | // 170 | this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); 171 | this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; 172 | this.ClientSize = new System.Drawing.Size(486, 461); 173 | this.Controls.Add(this.button1); 174 | this.Controls.Add(this.groupBox1); 175 | this.Controls.Add(this.pictureBox1); 176 | this.Controls.Add(this.textBox1); 177 | this.Controls.Add(this.dataGridView1); 178 | this.Name = "frmTCPServer"; 179 | this.Text = "TCPServer"; 180 | this.Load += new System.EventHandler(this.frmTCPServer_Load); 181 | ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit(); 182 | ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit(); 183 | this.groupBox1.ResumeLayout(false); 184 | this.groupBox1.PerformLayout(); 185 | this.ResumeLayout(false); 186 | this.PerformLayout(); 187 | 188 | } 189 | 190 | #endregion 191 | 192 | private System.Windows.Forms.DataGridView dataGridView1; 193 | private System.Windows.Forms.DataGridViewTextBoxColumn Column1; 194 | private System.Windows.Forms.DataGridViewTextBoxColumn Column2; 195 | private System.Windows.Forms.DataGridViewTextBoxColumn Column3; 196 | private System.Windows.Forms.DataGridViewTextBoxColumn Column4; 197 | private System.Windows.Forms.TextBox textBox1; 198 | private System.Windows.Forms.PictureBox pictureBox1; 199 | private System.Windows.Forms.GroupBox groupBox1; 200 | private System.Windows.Forms.Button button3; 201 | private System.Windows.Forms.TextBox textBox3; 202 | private System.Windows.Forms.Button button2; 203 | private System.Windows.Forms.TextBox textBox2; 204 | private System.Windows.Forms.Button button1; 205 | 206 | 207 | } 208 | } 209 | 210 | -------------------------------------------------------------------------------- /TCPServer/frmTCPServer.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.ComponentModel; 4 | using System.Data; 5 | using System.Drawing; 6 | using System.Linq; 7 | using System.Text; 8 | using System.Windows.Forms; 9 | using TJSYXY.Communication.TCP; 10 | using TJSYXY.Communication; 11 | using System.IO; 12 | using System.Drawing.Imaging; 13 | 14 | namespace TCPServer 15 | { 16 | /// 17 | /// 服务器窗体 简单的使用datagridview维护在线列表 18 | /// 19 | public partial class frmTCPServer : Form 20 | { 21 | private string _server_id; 22 | private int _port; 23 | 24 | public frmTCPServer() 25 | { 26 | InitializeComponent(); 27 | } 28 | public frmTCPServer(string server_id, int port) 29 | : this() 30 | { 31 | _server_id = server_id; 32 | _port = port; 33 | } 34 | 35 | /// 36 | /// 窗体加载 37 | /// 38 | /// 39 | /// 40 | private void frmTCPServer_Load(object sender, EventArgs e) 41 | { 42 | Text = "TCPServer " + _server_id + ":" + _port; 43 | 44 | //注册事件 45 | TCPServerManager manager = new TCPServerManager(_server_id); //访问_server_id服务器 46 | manager.TCPMessageReceived += new TCPMessageReceivedEventHandler(manager_TCPMessageReceived); 47 | manager.TCPClientConnected += new TCPClientConnectedEventHandler(manager_TCPClientConnected); 48 | manager.TCPClientDisConnected += new TCPClientDisConnectedEventHandler(manager_TCPClientDisConnected); 49 | manager.TCPClientDisConnected4Pulse += new TCPClientDisConnected4PulseEventHandler(manager_TCPClientDisConnected4Pulse); 50 | } 51 | 52 | #region 53 | /// 54 | /// 心跳检测时用户断线 55 | /// 56 | /// 57 | /// 58 | void manager_TCPClientDisConnected4Pulse(string csID, int uid) 59 | { 60 | this.Invoke((Action)delegate() 61 | { 62 | foreach (DataGridViewRow row in dataGridView1.Rows) 63 | { 64 | if (row.Cells[0].Value.ToString() == uid.ToString()) 65 | { 66 | dataGridView1.Rows.Remove(row); 67 | break; 68 | } 69 | } 70 | textBox1.AppendText("未收到终端唯一标识为[" + uid + "]的心跳包\n"); 71 | }); 72 | } 73 | /// 74 | /// 用户断线 75 | /// 76 | /// 77 | /// 78 | void manager_TCPClientDisConnected(string csID, TCPClientDisConnectedEventArgs args) 79 | { 80 | this.Invoke((Action)delegate() 81 | { 82 | foreach (DataGridViewRow row in dataGridView1.Rows) 83 | { 84 | if (row.Cells[0].Value.ToString() == args.End.UID.ToString()) 85 | { 86 | dataGridView1.Rows.Remove(row); 87 | break; 88 | } 89 | } 90 | textBox1.AppendText(args.Time.ToLongTimeString() + " 终端唯一标识为[" + args.End.UID + "]的用户下线\n"); 91 | 92 | }); 93 | } 94 | //用户上线 这里简单的使用datagridview.tag属性维护在线用户列表 95 | void manager_TCPClientConnected(string csID, TCPClientConnectedEventArgs args) 96 | { 97 | this.Invoke((Action)delegate() 98 | { 99 | textBox1.AppendText(args.Time.ToLongTimeString() + " " + args.End.RemoteIP + ":" + args.End.RemotePort + "连入\n"); 100 | dataGridView1.Rows.Add(args.End.UID, args.End.RemoteIP, args.End.RemotePort, args.Time.ToLongTimeString()); 101 | dataGridView1.Rows[dataGridView1.Rows.Count - 1].Tag = args.End; //可以自定义数据结构来存储在线列表 102 | }); 103 | } 104 | //收到消息 105 | void manager_TCPMessageReceived(string csID, TCPMessageReceivedEventArgs args) 106 | { 107 | this.Invoke((Action)delegate() 108 | { 109 | if (args.Msg == Msg.Zmsg1) //文本 110 | { 111 | textBox1.AppendText(args.Time.ToLongTimeString() + " " + args.End.RemoteIP + ":" + args.End.RemotePort + " 发送文本:\n" 112 | + Encoding.Unicode.GetString(args.Data) + "\n"); 113 | } 114 | if (args.Msg == Msg.Zmsg2) //图片 115 | { 116 | textBox1.AppendText(args.Time.ToLongTimeString() + " " + args.End.RemoteIP + ":" + args.End.RemotePort + " 发送图片:\n" 117 | + "见右方-->\n"); 118 | Image image = Bitmap.FromStream(new MemoryStream(args.Data)); 119 | pictureBox1.Image = image; 120 | } 121 | }); 122 | } 123 | #endregion 124 | 125 | /// 126 | /// 发送文本 127 | /// 128 | /// 129 | /// 130 | private void button2_Click(object sender, EventArgs e) 131 | { 132 | TCPServerManager manager = new TCPServerManager(_server_id); 133 | foreach (DataGridViewRow row in dataGridView1.Rows) 134 | { 135 | manager.Send(Msg.Zmsg1, Encoding.Unicode.GetBytes(textBox2.Text), row.Tag as TCPEndPoint); //给在线用户同步发送文本 136 | } 137 | } 138 | /// 139 | /// 发送图片 140 | /// 141 | /// 142 | /// 143 | private void button3_Click(object sender, EventArgs e) 144 | { 145 | using (OpenFileDialog ofd = new OpenFileDialog()) 146 | { 147 | ofd.Filter = "图片文件|*.jpg;*jpeg"; 148 | if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK) 149 | { 150 | textBox3.Text = ofd.FileName; 151 | Image image = Image.FromFile(textBox3.Text); 152 | using (MemoryStream ms = new MemoryStream()) 153 | { 154 | image.Save(ms, ImageFormat.Jpeg); 155 | 156 | TCPServerManager manager = new TCPServerManager(_server_id); 157 | foreach (DataGridViewRow r in dataGridView1.Rows) 158 | { 159 | manager.SendAsync(Msg.Zmsg2, ms.ToArray(), r.Tag as TCPEndPoint, null); //给在线用户异步发送图片 160 | } 161 | } 162 | } 163 | } 164 | } 165 | /// 166 | /// 关闭服务器 167 | /// 168 | /// 169 | /// 170 | private void button1_Click(object sender, EventArgs e) 171 | { 172 | TCPServerManager manager = new TCPServerManager(_server_id); 173 | manager.Stop(); //结束服务器侦听 174 | 175 | foreach (DataGridViewRow r in dataGridView1.Rows) //断开每个终端 数据接收终止 176 | { 177 | (r.Tag as TCPEndPoint).TryClose(); 178 | } 179 | //注销事件 180 | 181 | Close(); 182 | } 183 | } 184 | } 185 | -------------------------------------------------------------------------------- /TCPServer/frmTCPServer.resx: -------------------------------------------------------------------------------- 1 |  2 | 3 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | text/microsoft-resx 110 | 111 | 112 | 2.0 113 | 114 | 115 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 116 | 117 | 118 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 119 | 120 | 121 | True 122 | 123 | 124 | True 125 | 126 | 127 | True 128 | 129 | 130 | True 131 | 132 | 133 | True 134 | 135 | 136 | True 137 | 138 | 139 | True 140 | 141 | 142 | True 143 | 144 | -------------------------------------------------------------------------------- /TJSYXY.Communication.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 11.00 3 | # Visual Studio 2010 4 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TJSYXY.Communication", "TJSYXY.Communication\TJSYXY.Communication.csproj", "{F2B5C19C-218D-48E0-9BA1-32673F1352B7}" 5 | EndProject 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TCPServer", "TCPServer\TCPServer.csproj", "{75FA619B-F5AA-4328-BC8B-759B8A12F77C}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TCPClient", "TCPClient\TCPClient.csproj", "{2E4F81C6-21C2-4326-9684-0470B027FCA7}" 9 | EndProject 10 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UDPClient", "UDPClient\UDPClient.csproj", "{07A276C5-E93D-4F7E-9889-7FC1EAEFA85F}" 11 | EndProject 12 | Global 13 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 14 | Debug|Any CPU = Debug|Any CPU 15 | Debug|Mixed Platforms = Debug|Mixed Platforms 16 | Debug|x86 = Debug|x86 17 | Release|Any CPU = Release|Any CPU 18 | Release|Mixed Platforms = Release|Mixed Platforms 19 | Release|x86 = Release|x86 20 | EndGlobalSection 21 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 22 | {F2B5C19C-218D-48E0-9BA1-32673F1352B7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 23 | {F2B5C19C-218D-48E0-9BA1-32673F1352B7}.Debug|Any CPU.Build.0 = Debug|Any CPU 24 | {F2B5C19C-218D-48E0-9BA1-32673F1352B7}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU 25 | {F2B5C19C-218D-48E0-9BA1-32673F1352B7}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU 26 | {F2B5C19C-218D-48E0-9BA1-32673F1352B7}.Debug|x86.ActiveCfg = Debug|Any CPU 27 | {F2B5C19C-218D-48E0-9BA1-32673F1352B7}.Release|Any CPU.ActiveCfg = Release|Any CPU 28 | {F2B5C19C-218D-48E0-9BA1-32673F1352B7}.Release|Any CPU.Build.0 = Release|Any CPU 29 | {F2B5C19C-218D-48E0-9BA1-32673F1352B7}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU 30 | {F2B5C19C-218D-48E0-9BA1-32673F1352B7}.Release|Mixed Platforms.Build.0 = Release|Any CPU 31 | {F2B5C19C-218D-48E0-9BA1-32673F1352B7}.Release|x86.ActiveCfg = Release|Any CPU 32 | {75FA619B-F5AA-4328-BC8B-759B8A12F77C}.Debug|Any CPU.ActiveCfg = Debug|x86 33 | {75FA619B-F5AA-4328-BC8B-759B8A12F77C}.Debug|Mixed Platforms.ActiveCfg = Debug|x86 34 | {75FA619B-F5AA-4328-BC8B-759B8A12F77C}.Debug|Mixed Platforms.Build.0 = Debug|x86 35 | {75FA619B-F5AA-4328-BC8B-759B8A12F77C}.Debug|x86.ActiveCfg = Debug|x86 36 | {75FA619B-F5AA-4328-BC8B-759B8A12F77C}.Debug|x86.Build.0 = Debug|x86 37 | {75FA619B-F5AA-4328-BC8B-759B8A12F77C}.Release|Any CPU.ActiveCfg = Release|x86 38 | {75FA619B-F5AA-4328-BC8B-759B8A12F77C}.Release|Mixed Platforms.ActiveCfg = Release|x86 39 | {75FA619B-F5AA-4328-BC8B-759B8A12F77C}.Release|Mixed Platforms.Build.0 = Release|x86 40 | {75FA619B-F5AA-4328-BC8B-759B8A12F77C}.Release|x86.ActiveCfg = Release|x86 41 | {75FA619B-F5AA-4328-BC8B-759B8A12F77C}.Release|x86.Build.0 = Release|x86 42 | {2E4F81C6-21C2-4326-9684-0470B027FCA7}.Debug|Any CPU.ActiveCfg = Debug|x86 43 | {2E4F81C6-21C2-4326-9684-0470B027FCA7}.Debug|Mixed Platforms.ActiveCfg = Debug|x86 44 | {2E4F81C6-21C2-4326-9684-0470B027FCA7}.Debug|Mixed Platforms.Build.0 = Debug|x86 45 | {2E4F81C6-21C2-4326-9684-0470B027FCA7}.Debug|x86.ActiveCfg = Debug|x86 46 | {2E4F81C6-21C2-4326-9684-0470B027FCA7}.Debug|x86.Build.0 = Debug|x86 47 | {2E4F81C6-21C2-4326-9684-0470B027FCA7}.Release|Any CPU.ActiveCfg = Release|x86 48 | {2E4F81C6-21C2-4326-9684-0470B027FCA7}.Release|Mixed Platforms.ActiveCfg = Release|x86 49 | {2E4F81C6-21C2-4326-9684-0470B027FCA7}.Release|Mixed Platforms.Build.0 = Release|x86 50 | {2E4F81C6-21C2-4326-9684-0470B027FCA7}.Release|x86.ActiveCfg = Release|x86 51 | {2E4F81C6-21C2-4326-9684-0470B027FCA7}.Release|x86.Build.0 = Release|x86 52 | {07A276C5-E93D-4F7E-9889-7FC1EAEFA85F}.Debug|Any CPU.ActiveCfg = Debug|x86 53 | {07A276C5-E93D-4F7E-9889-7FC1EAEFA85F}.Debug|Mixed Platforms.ActiveCfg = Debug|x86 54 | {07A276C5-E93D-4F7E-9889-7FC1EAEFA85F}.Debug|Mixed Platforms.Build.0 = Debug|x86 55 | {07A276C5-E93D-4F7E-9889-7FC1EAEFA85F}.Debug|x86.ActiveCfg = Debug|x86 56 | {07A276C5-E93D-4F7E-9889-7FC1EAEFA85F}.Debug|x86.Build.0 = Debug|x86 57 | {07A276C5-E93D-4F7E-9889-7FC1EAEFA85F}.Release|Any CPU.ActiveCfg = Release|x86 58 | {07A276C5-E93D-4F7E-9889-7FC1EAEFA85F}.Release|Mixed Platforms.ActiveCfg = Release|x86 59 | {07A276C5-E93D-4F7E-9889-7FC1EAEFA85F}.Release|Mixed Platforms.Build.0 = Release|x86 60 | {07A276C5-E93D-4F7E-9889-7FC1EAEFA85F}.Release|x86.ActiveCfg = Release|x86 61 | {07A276C5-E93D-4F7E-9889-7FC1EAEFA85F}.Release|x86.Build.0 = Release|x86 62 | EndGlobalSection 63 | GlobalSection(SolutionProperties) = preSolution 64 | HideSolutionNode = FALSE 65 | EndGlobalSection 66 | EndGlobal 67 | -------------------------------------------------------------------------------- /TJSYXY.Communication.suo: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sherlockchou86/TJSYXYCommunication/b648c1ebfdead71712477588e363de7e77aef20f/TJSYXY.Communication.suo -------------------------------------------------------------------------------- /TJSYXY.Communication/Msg.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace TJSYXY.Communication 6 | { 7 | /// 8 | /// 说明: 9 | /// 通讯消息类型(枚举项可增加) 10 | /// 信息: 11 | /// 周智 2015.07.20 12 | /// 13 | public enum Msg 14 | { 15 | Default = 0, //系统保留,TCP通信中用作心跳检测 16 | Zmsg1, 17 | Zmsg2, 18 | Zmsg3, 19 | Zmsg4, 20 | Zmsg5, 21 | Zmsg6, 22 | Zmsg7, 23 | Zmsg8, 24 | Zmsg9, 25 | Zmsg10, 26 | Zmsg11, 27 | Zmsg12, 28 | Zmsg13, 29 | Zmsg14, 30 | Zmsg15, 31 | Zmsg16, 32 | Zmsg17, 33 | Zmsg18, 34 | Zmsg19, 35 | Zmsg20, 36 | Zmsg21, 37 | Zmsg22, 38 | Zmsg23, 39 | Zmsg24, 40 | Zmsg25, 41 | Zmsg26, 42 | Zmsg27, 43 | Zmsg28, 44 | Zmsg29, 45 | Zmsg30, 46 | Zmsg31, 47 | Zmsg32, 48 | Zmsg33, 49 | Zmsg34, 50 | Zmsg35, 51 | Zmsg36, 52 | Zmsg37, 53 | Zmsg38, 54 | Zmsg39, 55 | Zmsg40, 56 | Zmsg41, 57 | Zmsg42, 58 | Zmsg43, 59 | Zmsg44, 60 | Zmsg45, 61 | Zmsg46, 62 | Zmsg47, 63 | Zmsg48, 64 | Zmsg49, 65 | Zmsg50, 66 | Zmsg51, 67 | Zmsg52, 68 | Zmsg53, 69 | Zmsg54, 70 | Zmsg55, 71 | Zmsg56, 72 | Zmsg57, 73 | Zmsg58, 74 | Zmsg59, 75 | Zmsg60, 76 | Zmsg61, 77 | Zmsg62, 78 | Zmsg63, 79 | Zmsg64, 80 | Zmsg65, 81 | Zmsg66, 82 | Zmsg67, 83 | Zmsg68, 84 | Zmsg69, 85 | Zmsg70, 86 | Zmsg71, 87 | Zmsg72, 88 | Zmsg73, 89 | Zmsg74, 90 | Zmsg75, 91 | Zmsg76, 92 | Zmsg77, 93 | Zmsg78, 94 | Zmsg79, 95 | Zmsg80, 96 | Zmsg81, 97 | Zmsg82, 98 | Zmsg83, 99 | Zmsg84, 100 | Zmsg85, 101 | Zmsg86, 102 | Zmsg87, 103 | Zmsg88, 104 | Zmsg89, 105 | Zmsg90, 106 | Zmsg91, 107 | Zmsg92, 108 | Zmsg93, 109 | Zmsg94, 110 | Zmsg95, 111 | Zmsg96, 112 | Zmsg97, 113 | Zmsg98, 114 | Zmsg99, 115 | Zmsg100 116 | } 117 | } 118 | -------------------------------------------------------------------------------- /TJSYXY.Communication/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("TJSYXY.Communication")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("TJSYXY.Communication")] 13 | [assembly: AssemblyCopyright("Copyright © 2015")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("d41fa397-9a53-4d9e-8a04-7086d054ab84")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /TJSYXY.Communication/TCP/TCPClient.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Net.Sockets; 5 | using System.Net; 6 | using System.IO; 7 | using System.ComponentModel; 8 | using System.Threading; 9 | 10 | namespace TJSYXY.Communication.TCP 11 | { 12 | /// 13 | /// 说明: 14 | /// TCP通信客户端 15 | /// 信息: 16 | /// 周智 2015.07.20 17 | /// 18 | class TCPClient 19 | { 20 | private Socket _socket; //客户端socket 21 | private string _client_id; //客户端ID 22 | 23 | private BackgroundWorker _pulse_test = new BackgroundWorker(); 24 | 25 | private int _pulse = 3; 26 | /// 27 | /// 心跳包发送时间间隔(应小于服务器端设置的Pulse) 28 | /// 29 | public int Pulse 30 | { 31 | get 32 | { 33 | return _pulse; 34 | } 35 | set 36 | { 37 | _pulse = value; 38 | } 39 | } 40 | 41 | private static Dictionary _tcpClients; 42 | /// 43 | /// 客户端列表 44 | /// 45 | public static Dictionary TCPClients 46 | { 47 | get 48 | { 49 | if (_tcpClients == null) 50 | { 51 | _tcpClients = new Dictionary(); 52 | } 53 | return _tcpClients; 54 | } 55 | } 56 | 57 | /// 58 | /// 客户端连接状态 59 | /// 60 | public bool Connected 61 | { 62 | get; 63 | set; 64 | } 65 | /// 66 | /// 接收到服务器的消息时激发该事件 67 | /// 68 | public event TCPMessageReceivedEventHandler TCPMessageReceived; 69 | /// 70 | /// 客户端连入服务器时激发该事件 71 | /// 72 | public event TCPClientConnectedEventHandler TCPClientConnected; 73 | /// 74 | /// 客户端断开服务器时激发该事件 75 | /// 76 | public event TCPClientDisConnectedEventHandler TCPClientDisConnected; 77 | /// 78 | /// 在心跳包发送时检测出客户端断线时激发该事件 79 | /// 80 | public event TCPClientDisConnected4PulseEventHandler TCPClientDisConnected4Pulse; 81 | 82 | /// 83 | /// 构造方法 84 | /// 85 | /// 客户端ID 86 | public TCPClient(string client_id) 87 | { 88 | _client_id = client_id; 89 | _pulse_test.DoWork += new DoWorkEventHandler(_pulse_test_DoWork); 90 | _pulse_test.RunWorkerAsync(); 91 | } 92 | /// 93 | /// 心跳包发送 94 | /// 95 | /// 96 | /// 97 | private void _pulse_test_DoWork(object sender, DoWorkEventArgs e) 98 | { 99 | while (!_pulse_test.CancellationPending) 100 | { 101 | try 102 | { 103 | if (Connected) 104 | { 105 | Send(Msg.Default, new byte[] { 0 }); //心跳包发送 106 | } 107 | } 108 | catch 109 | { 110 | if (TCPClientDisConnected4Pulse != null) 111 | { 112 | TCPClientDisConnected4Pulse(_client_id, -1); 113 | } 114 | } 115 | Thread.Sleep(_pulse * 1000); 116 | } 117 | } 118 | /// 119 | /// 连接服务器 120 | /// 121 | /// 服务器IP 122 | /// 服务器端口 123 | public void Connect(string ip, int port) 124 | { 125 | if (!Connected) 126 | { 127 | if (_socket == null) 128 | { 129 | _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 130 | } 131 | _socket.Connect(new IPEndPoint(IPAddress.Parse(ip), port)); 132 | Connected = true; 133 | TCPEndPoint end = new TCPEndPoint(); 134 | end.Socket = _socket; 135 | end.Socket.BeginReceive(end.Buffer, 0, 1024, SocketFlags.None, new AsyncCallback(OnReceive), end); 136 | if (TCPClientConnected != null) //通知新客户端连入 137 | { 138 | TCPClientConnectedEventArgs args = new TCPClientConnectedEventArgs(); 139 | args.End = end; 140 | args.Time = DateTime.Now; 141 | TCPClientConnected(_client_id, args); 142 | } 143 | } 144 | } 145 | /// 146 | /// 断开连接 147 | /// 148 | public void DisConnect() 149 | { 150 | if (Connected) 151 | { 152 | if (_socket != null) 153 | { 154 | _socket.Close(); 155 | _socket = null; 156 | } 157 | Connected = false; 158 | } 159 | } 160 | /// 161 | /// 接收数据回调方法 162 | /// 163 | /// 164 | private void OnReceive(IAsyncResult ar) 165 | { 166 | TCPEndPoint end = ar.AsyncState as TCPEndPoint; 167 | try 168 | { 169 | int real_recv = end.Socket.EndReceive(ar); 170 | end.MStream.Write(end.Buffer, 0, real_recv); //写入消息缓冲区 171 | //尝试读取一条完整消息 172 | ZMessage msg; 173 | while (end.MStream.ReadMessage(out msg)) 174 | { 175 | //处理消息 176 | if (TCPMessageReceived != null) 177 | { 178 | TCPMessageReceivedEventArgs args = new TCPMessageReceivedEventArgs(); 179 | args.Msg = (Msg)msg.head; 180 | args.Time = DateTime.Now; 181 | args.End = end; 182 | args.Data = msg.content; 183 | TCPMessageReceived.BeginInvoke(_client_id, args, null, null); //激发事件,通知事件注册者处理消息 184 | } 185 | } 186 | end.Socket.BeginReceive(end.Buffer, 0, 1024, SocketFlags.None, new AsyncCallback(OnReceive), end); 187 | } 188 | catch 189 | { 190 | if (TCPClientDisConnected != null) //通知客户端断开 191 | { 192 | TCPClientDisConnectedEventArgs args = new TCPClientDisConnectedEventArgs(); 193 | args.End = end; 194 | args.Time = DateTime.Now; 195 | TCPClientDisConnected(_client_id, args); 196 | } 197 | } 198 | } 199 | 200 | /// 201 | /// 向服务器同步发送数据 202 | /// 203 | /// 消息类型 204 | /// 消息数据正文 205 | public void Send(Msg msg, byte[] data) 206 | { 207 | byte[] buffer2send = new byte[5 + data.Length]; // 1 + 4 + data 208 | BinaryWriter sWriter = new BinaryWriter(new MemoryStream(buffer2send)); 209 | 210 | sWriter.Write((byte)msg); 211 | sWriter.Write(data.Length); 212 | sWriter.Write(data); 213 | sWriter.Close(); 214 | 215 | _socket.Send(buffer2send); //同步 216 | } 217 | /// 218 | /// 向服务器异步发送数据 219 | /// 220 | /// 消息类型 221 | /// 消息数据正文 222 | /// 回调方法 223 | public void SendAsync(Msg msg, byte[] data, AsyncCallback callback) 224 | { 225 | byte[] buffer2send = new byte[5 + data.Length]; // 1 + 4 + data 226 | BinaryWriter sWriter = new BinaryWriter(new MemoryStream(buffer2send)); 227 | 228 | sWriter.Write((byte)msg); 229 | sWriter.Write(data.Length); 230 | sWriter.Write(data); 231 | sWriter.Close(); 232 | 233 | _socket.BeginSend(buffer2send, 0, buffer2send.Length, SocketFlags.None, callback, _socket); //异步 234 | } 235 | } 236 | } 237 | -------------------------------------------------------------------------------- /TJSYXY.Communication/TCP/TCPClientManager.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace TJSYXY.Communication.TCP 6 | { 7 | /// 8 | /// 说明: 9 | /// TCP通信客户端的代理 10 | /// 信息: 11 | /// 周智 2015.07.20 12 | /// 13 | public class TCPClientManager 14 | { 15 | private string _client_id; //要代理的客户端ID 16 | 17 | /// 18 | /// 构造方法 19 | /// 20 | /// 要代理的客户端ID,若不存在,则使用该client_id创建 21 | public TCPClientManager(string client_id) 22 | { 23 | _client_id = client_id; 24 | if (!TCPClient.TCPClients.ContainsKey(_client_id)) 25 | { 26 | TCPClient.TCPClients.Add(_client_id, new TCPClient(_client_id)); 27 | } 28 | } 29 | /// 30 | /// 客户端连接状态 31 | /// 32 | public bool Connected 33 | { 34 | get 35 | { 36 | return TCPClient.TCPClients[_client_id].Connected; 37 | } 38 | } 39 | /// 40 | /// 心跳包发送时间间隔,默认为3秒(应小于服务器端Pulse) 41 | /// 42 | public int Pulse 43 | { 44 | get 45 | { 46 | return TCPClient.TCPClients[_client_id].Pulse; 47 | } 48 | set 49 | { 50 | TCPClient.TCPClients[_client_id].Pulse = value; 51 | } 52 | } 53 | /// 54 | /// 检查指定客户端是否存在 55 | /// 56 | /// 57 | /// 58 | public static bool ClientExist(string client_id) 59 | { 60 | return TCPClient.TCPClients.ContainsKey(client_id); 61 | } 62 | 63 | /// 64 | /// 连接服务器 65 | /// 66 | /// 服务器IP 67 | /// 服务器端口 68 | public void Connect(string ip, int port) 69 | { 70 | TCPClient.TCPClients[_client_id].Connect(ip, port); 71 | } 72 | /// 73 | /// 断开服务器 74 | /// 75 | public void DisConnect() 76 | { 77 | TCPClient.TCPClients[_client_id].DisConnect(); 78 | } 79 | /// 80 | /// 向服务器同步发送数据 81 | /// 82 | /// 消息类型 83 | /// 消息数据正文 84 | public void Send(Msg msg, byte[] data) 85 | { 86 | TCPClient.TCPClients[_client_id].Send(msg, data); 87 | } 88 | /// 89 | /// 向服务器异步发送数据 90 | /// 91 | /// 消息类型 92 | /// 消息数据正文 93 | /// 回调方法 94 | public void SendAsync(Msg msg, byte[] data, AsyncCallback callback) 95 | { 96 | TCPClient.TCPClients[_client_id].SendAsync(msg, data, callback); 97 | } 98 | 99 | /// 100 | /// 接收到服务器的消息时激发该事件 101 | /// 102 | public event TCPMessageReceivedEventHandler TCPMessageReceived 103 | { 104 | add 105 | { 106 | TCPClient.TCPClients[_client_id].TCPMessageReceived += value; 107 | } 108 | remove 109 | { 110 | TCPClient.TCPClients[_client_id].TCPMessageReceived -= value; 111 | } 112 | } 113 | /// 114 | /// 客户端连入服务器时激发该事件 115 | /// 116 | public event TCPClientConnectedEventHandler TCPClientConnected 117 | { 118 | add 119 | { 120 | TCPClient.TCPClients[_client_id].TCPClientConnected += value; 121 | } 122 | remove 123 | { 124 | TCPClient.TCPClients[_client_id].TCPClientConnected -= value; 125 | } 126 | } 127 | /// 128 | /// 客户端断开服务器时激发该事件 129 | /// 130 | public event TCPClientDisConnectedEventHandler TCPClientDisConnected 131 | { 132 | add 133 | { 134 | TCPClient.TCPClients[_client_id].TCPClientDisConnected += value; 135 | } 136 | remove 137 | { 138 | TCPClient.TCPClients[_client_id].TCPClientDisConnected -= value; 139 | } 140 | } 141 | /// 142 | /// 在心跳包发送时检测出断线时激发该事件 143 | /// 144 | public event TCPClientDisConnected4PulseEventHandler TCPClientDisConnected4Pulse 145 | { 146 | add 147 | { 148 | TCPClient.TCPClients[_client_id].TCPClientDisConnected4Pulse += value; 149 | } 150 | remove 151 | { 152 | TCPClient.TCPClients[_client_id].TCPClientDisConnected4Pulse -= value; 153 | } 154 | } 155 | } 156 | } 157 | -------------------------------------------------------------------------------- /TJSYXY.Communication/TCP/TCPEndPoint.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Net.Sockets; 5 | using System.Net; 6 | 7 | namespace TJSYXY.Communication.TCP 8 | { 9 | /// 10 | /// 说明: 11 | /// TCP通信过程中的终端 12 | /// 信息: 13 | /// 周智 2015.07.20 14 | /// 15 | public class TCPEndPoint 16 | { 17 | private Socket _socket; //负责通信的Socket 18 | private byte[] _buffer = new byte[1024]; //接收数据系统缓冲区 19 | private ZMessageStream _mStream = new ZMessageStream(); //消息缓冲区 20 | 21 | /// 22 | /// 负责通信的Socket 23 | /// 24 | internal Socket Socket 25 | { 26 | get 27 | { 28 | return _socket; 29 | } 30 | set 31 | { 32 | _socket = value; 33 | } 34 | } 35 | /// 36 | /// 接收数据系统缓冲区 37 | /// 38 | internal byte[] Buffer 39 | { 40 | get 41 | { 42 | return _buffer; 43 | } 44 | } 45 | /// 46 | /// 消息缓冲区 47 | /// 48 | internal ZMessageStream MStream 49 | { 50 | get 51 | { 52 | return _mStream; 53 | } 54 | } 55 | /// 56 | /// 终端唯一标识[服务器端有效] 57 | /// 58 | public int UID 59 | { 60 | get; 61 | set; 62 | } 63 | /// 64 | /// 远程终端IP 65 | /// 66 | public string RemoteIP 67 | { 68 | get 69 | { 70 | try 71 | { 72 | return ((IPEndPoint)_socket.RemoteEndPoint).Address.ToString(); 73 | } 74 | catch 75 | { 76 | return null; 77 | } 78 | } 79 | } 80 | /// 81 | /// 远程终端Port 82 | /// 83 | public int RemotePort 84 | { 85 | get 86 | { 87 | try 88 | { 89 | return ((IPEndPoint)_socket.RemoteEndPoint).Port; 90 | } 91 | catch 92 | { 93 | return -1; 94 | } 95 | } 96 | } 97 | /// 98 | /// 尝试关闭当前Socket连接 99 | /// 100 | public void TryClose() 101 | { 102 | try 103 | { 104 | _socket.Close(); 105 | } 106 | catch 107 | { 108 | 109 | } 110 | } 111 | } 112 | } 113 | -------------------------------------------------------------------------------- /TJSYXY.Communication/TCP/TCPServer.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Net.Sockets; 5 | using System.Net; 6 | using System.IO; 7 | using System.Collections.Concurrent; 8 | using System.ComponentModel; 9 | 10 | namespace TJSYXY.Communication.TCP 11 | { 12 | /// 13 | /// 说明: 14 | /// TCP通信服务器 15 | /// 信息: 16 | /// 周智 2015.07.20 17 | /// 18 | class TCPServer 19 | { 20 | private Socket _socket; //服务端监听socket 21 | private string _server_id; //服务器ID 22 | private int _client_index; //当前连入客户端index 23 | 24 | private ConcurrentDictionary _pulse_time = new ConcurrentDictionary(); 25 | private BackgroundWorker _pulse_test = new BackgroundWorker(); 26 | 27 | private static Dictionary _tcpServers; 28 | /// 29 | /// 服务器列表 30 | /// 31 | public static Dictionary TCPServers 32 | { 33 | get 34 | { 35 | if (_tcpServers == null) 36 | { 37 | _tcpServers = new Dictionary(); 38 | } 39 | return _tcpServers; 40 | } 41 | } 42 | /// 43 | /// 服务器状态 44 | /// 45 | public bool Runing 46 | { 47 | get; 48 | set; 49 | } 50 | 51 | private int _pulse = 5; 52 | /// 53 | /// 服务器端心跳检测时间 54 | /// 55 | public int Pulse 56 | { 57 | get 58 | { 59 | return _pulse; 60 | } 61 | set 62 | { 63 | _pulse = value; 64 | } 65 | } 66 | 67 | /// 68 | /// 接收到TCP消息时激发该事件 69 | /// 70 | public event TCPMessageReceivedEventHandler TCPMessageReceived; 71 | /// 72 | /// 客户端连入服务器时激发该事件 73 | /// 74 | public event TCPClientConnectedEventHandler TCPClientConnected; 75 | /// 76 | /// 客户端断开服务器时激发该事件 77 | /// 78 | public event TCPClientDisConnectedEventHandler TCPClientDisConnected; 79 | /// 80 | /// 在心跳检测发现断线时激发该事件 81 | /// 82 | public event TCPClientDisConnected4PulseEventHandler TCPClientDisConnected4Pulse; 83 | 84 | /// 85 | /// 构造方法 86 | /// 87 | /// 服务器ID 88 | public TCPServer(string server_id) 89 | { 90 | _server_id = server_id; 91 | _pulse_test.DoWork += new DoWorkEventHandler(_pulse_test_DoWork); 92 | _pulse_test.RunWorkerAsync(); 93 | } 94 | /// 95 | /// 心跳检测 96 | /// 97 | /// 98 | /// 99 | private void _pulse_test_DoWork(object sender, DoWorkEventArgs e) 100 | { 101 | while (!_pulse_test.CancellationPending) 102 | { 103 | foreach (KeyValuePair p in _pulse_time) 104 | { 105 | _pulse_time[p.Key] = p.Value - 1; 106 | if (_pulse_time[p.Key] == 0) //心跳检测断线 107 | { 108 | if (TCPClientDisConnected4Pulse != null) 109 | { 110 | TCPClientDisConnected4Pulse(_server_id, p.Key); 111 | } 112 | } 113 | } 114 | System.Threading.Thread.Sleep(1000); 115 | } 116 | } 117 | 118 | /// 119 | /// 按照给定的端口号开启服务器 120 | /// 121 | /// 侦听端口号 122 | public void Start(int port) 123 | { 124 | if (!Runing) 125 | { 126 | string ip = Dns.GetHostByName(Dns.GetHostName()).AddressList[0].ToString(); 127 | if (_socket == null) 128 | { 129 | _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 130 | } 131 | _socket.Bind(new IPEndPoint(IPAddress.Parse(ip), port)); 132 | _socket.Listen(256); 133 | _socket.BeginAccept(new AsyncCallback(OnAccept), null); //开始第一次接受客户端连接 134 | Runing = true; 135 | } 136 | } 137 | /// 138 | /// 关闭服务器 139 | /// 140 | public void Stop() 141 | { 142 | if (Runing) 143 | { 144 | if (_socket != null) 145 | { 146 | _socket.Close(); 147 | _socket = null; 148 | } 149 | Runing = false; 150 | } 151 | } 152 | 153 | /// 154 | /// 客户端连入回调方法 155 | /// 156 | /// 157 | private void OnAccept(IAsyncResult ar) 158 | { 159 | try 160 | { 161 | Socket new_socket = _socket.EndAccept(ar); 162 | TCPEndPoint end = new TCPEndPoint(); 163 | end.Socket = new_socket; 164 | end.UID = _client_index++; 165 | end.Socket.BeginReceive(end.Buffer, 0, 1024, SocketFlags.None, new AsyncCallback(OnReceive), end); //开始第一次数据接收 166 | _socket.BeginAccept(new AsyncCallback(OnAccept), null); //开始接受下一次客户端连接 167 | _pulse_time.TryAdd(end.UID, _pulse); //加入心跳检测 168 | if (TCPClientConnected != null) //通知新客户端连入 169 | { 170 | TCPClientConnectedEventArgs args = new TCPClientConnectedEventArgs(); 171 | args.End = end; 172 | args.Time = DateTime.Now; 173 | TCPClientConnected(_server_id, args); 174 | } 175 | } 176 | catch 177 | { 178 | 179 | } 180 | } 181 | /// 182 | /// 接收数据回调方法 183 | /// 184 | /// 回调参数 185 | private void OnReceive(IAsyncResult ar) 186 | { 187 | TCPEndPoint end = ar.AsyncState as TCPEndPoint; 188 | try 189 | { 190 | int real_recv = end.Socket.EndReceive(ar); 191 | end.MStream.Write(end.Buffer, 0, real_recv); //写入消息缓冲区 192 | //尝试读取一条完整消息 193 | ZMessage msg; 194 | while (end.MStream.ReadMessage(out msg)) 195 | { 196 | if ((Msg)msg.head == Msg.Default) //心跳包 跳过 197 | { 198 | foreach (KeyValuePair p in _pulse_time) 199 | { 200 | if (p.Key == end.UID) 201 | { 202 | _pulse_time[p.Key] = _pulse; //重置 203 | break; 204 | } 205 | } 206 | continue; 207 | } 208 | //处理消息 209 | if (TCPMessageReceived != null) 210 | { 211 | TCPMessageReceivedEventArgs args = new TCPMessageReceivedEventArgs(); 212 | args.Msg = (Msg)msg.head; 213 | args.Time = DateTime.Now; 214 | args.End = end; 215 | args.Data = msg.content; 216 | TCPMessageReceived.BeginInvoke(_server_id, args, null, null); //激发事件,通知事件注册者处理消息 217 | } 218 | } 219 | end.Socket.BeginReceive(end.Buffer, 0, 1024, SocketFlags.None, new AsyncCallback(OnReceive), end); //开始下一次数据接收 220 | } 221 | catch 222 | { 223 | if (TCPClientDisConnected != null) //通知客户端断开 224 | { 225 | TCPClientDisConnectedEventArgs args = new TCPClientDisConnectedEventArgs(); 226 | args.End = end; 227 | args.Time = DateTime.Now; 228 | TCPClientDisConnected(_server_id, args); 229 | } 230 | int tmp; 231 | _pulse_time.TryRemove(end.UID,out tmp); 232 | } 233 | } 234 | 235 | /// 236 | /// 给指定终端同步发送数据 237 | /// 238 | /// 消息类型 239 | /// 消息数据正文 240 | /// 指定终端 241 | public void Send(Msg msg, byte[] data, TCPEndPoint end) 242 | { 243 | byte[] buffer2send = new byte[5 + data.Length]; // 1 + 4 + data 244 | BinaryWriter sWriter = new BinaryWriter(new MemoryStream(buffer2send)); 245 | 246 | sWriter.Write((byte)msg); 247 | sWriter.Write(data.Length); 248 | sWriter.Write(data); 249 | sWriter.Close(); 250 | 251 | end.Socket.Send(buffer2send); //同步 252 | } 253 | /// 254 | /// 给指定终端异步发送数据 255 | /// 256 | /// 消息类型 257 | /// 消息数据正文 258 | /// 指定终端 259 | /// 回调方法 260 | public void SendAsync(Msg msg, byte[] data, TCPEndPoint end, AsyncCallback callback) 261 | { 262 | byte[] buffer2send = new byte[5 + data.Length]; // 1 + 4 + data 263 | BinaryWriter sWriter = new BinaryWriter(new MemoryStream(buffer2send)); 264 | 265 | sWriter.Write((byte)msg); 266 | sWriter.Write(data.Length); 267 | sWriter.Write(data); 268 | sWriter.Close(); 269 | 270 | end.Socket.BeginSend(buffer2send, 0, buffer2send.Length, SocketFlags.None, callback, end); //异步 271 | } 272 | } 273 | } 274 | -------------------------------------------------------------------------------- /TJSYXY.Communication/TCP/TCPServerManager.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace TJSYXY.Communication.TCP 6 | { 7 | /// 8 | /// 说明: 9 | /// TCP通信服务器的代理 10 | /// 信息: 11 | /// 周智 2015.07.20 12 | /// 13 | public class TCPServerManager 14 | { 15 | private string _server_id; //当前要代理的服务器ID 16 | 17 | /// 18 | /// 构造方法 19 | /// 20 | /// 要代理的服务器id,若不存在,则使用server_id创建 21 | public TCPServerManager(string server_id) 22 | { 23 | _server_id = server_id; 24 | if (!TCPServer.TCPServers.ContainsKey(server_id)) 25 | { 26 | TCPServer.TCPServers.Add(server_id, new TCPServer(server_id)); 27 | } 28 | } 29 | /// 30 | /// 启动服务器 31 | /// 32 | /// 侦听端口号 33 | public void Start(int port) 34 | { 35 | TCPServer.TCPServers[_server_id].Start(port); 36 | } 37 | /// 38 | /// 关闭服务器,只结束侦听 39 | /// 40 | public void Stop() 41 | { 42 | TCPServer.TCPServers[_server_id].Stop(); 43 | } 44 | /// 45 | /// 向指定终端同步发送数据 46 | /// 47 | /// 消息类型 48 | /// 消息数据正文 49 | /// 指定终端 50 | public void Send(Msg msg, byte[] data, TCPEndPoint end) 51 | { 52 | TCPServer.TCPServers[_server_id].Send(msg, data, end); 53 | } 54 | /// 55 | /// 向指定终端异步发送数据 56 | /// 57 | /// 消息类型 58 | /// 消息数据正文 59 | /// 指定终端 60 | /// 回调方法 61 | public void SendAsync(Msg msg, byte[] data, TCPEndPoint end, AsyncCallback callback) 62 | { 63 | TCPServer.TCPServers[_server_id].SendAsync(msg, data, end, callback); 64 | } 65 | 66 | /// 67 | /// 服务器接收到消息时激发该事件 68 | /// 69 | public event TCPMessageReceivedEventHandler TCPMessageReceived 70 | { 71 | add 72 | { 73 | TCPServer.TCPServers[_server_id].TCPMessageReceived += value; 74 | } 75 | remove 76 | { 77 | TCPServer.TCPServers[_server_id].TCPMessageReceived -= value; 78 | } 79 | } 80 | /// 81 | /// 客户端连入服务器时激发该事件 82 | /// 83 | public event TCPClientConnectedEventHandler TCPClientConnected 84 | { 85 | add 86 | { 87 | TCPServer.TCPServers[_server_id].TCPClientConnected += value; 88 | } 89 | remove 90 | { 91 | TCPServer.TCPServers[_server_id].TCPClientConnected -= value; 92 | } 93 | } 94 | /// 95 | /// 客户端断开服务器时激发该事件 96 | /// 97 | public event TCPClientDisConnectedEventHandler TCPClientDisConnected 98 | { 99 | add 100 | { 101 | TCPServer.TCPServers[_server_id].TCPClientDisConnected += value; 102 | } 103 | remove 104 | { 105 | TCPServer.TCPServers[_server_id].TCPClientDisConnected -= value; 106 | } 107 | } 108 | /// 109 | /// 在心跳检测发现断线时激发该事件 110 | /// 111 | public event TCPClientDisConnected4PulseEventHandler TCPClientDisConnected4Pulse 112 | { 113 | add 114 | { 115 | TCPServer.TCPServers[_server_id].TCPClientDisConnected4Pulse += value; 116 | } 117 | remove 118 | { 119 | TCPServer.TCPServers[_server_id].TCPClientDisConnected4Pulse -= value; 120 | } 121 | } 122 | 123 | /// 124 | /// 服务器状态 125 | /// 126 | public bool Runing 127 | { 128 | get 129 | { 130 | return TCPServer.TCPServers[_server_id].Runing; 131 | } 132 | } 133 | /// 134 | /// 服务器心跳检测时间,默认为5秒(应大于客户端的Pulse) 135 | /// 136 | public int Pulse 137 | { 138 | get 139 | { 140 | return TCPServer.TCPServers[_server_id].Pulse; 141 | } 142 | set 143 | { 144 | TCPServer.TCPServers[_server_id].Pulse = value; 145 | } 146 | } 147 | /// 148 | /// 检查指定服务器是否存在 149 | /// 150 | /// 151 | /// 152 | public static bool ServerExist(string server_id) 153 | { 154 | return TCPServer.TCPServers.ContainsKey(server_id); 155 | } 156 | } 157 | } 158 | -------------------------------------------------------------------------------- /TJSYXY.Communication/TCP/TCPs.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace TJSYXY.Communication.TCP 6 | { 7 | /// 8 | /// TCP消息参数 9 | /// 10 | public class TCPMessageReceivedEventArgs : EventArgs 11 | { 12 | /// 13 | /// 消息类型 14 | /// 15 | public Msg Msg 16 | { 17 | get; 18 | set; 19 | } 20 | /// 21 | /// 消息数据 22 | /// 23 | public byte[] Data 24 | { 25 | set; 26 | get; 27 | } 28 | /// 29 | /// 终端 30 | /// 31 | public TCPEndPoint End 32 | { 33 | get; 34 | set; 35 | } 36 | /// 37 | /// 消息接收时间 38 | /// 39 | public DateTime Time 40 | { 41 | get; 42 | set; 43 | } 44 | } 45 | /// 46 | /// 表示处理TCP消息的方法 47 | /// 48 | /// 激发该事件的服务器(或客户端)ID 49 | /// 消息参数 50 | public delegate void TCPMessageReceivedEventHandler(string csID, TCPMessageReceivedEventArgs args); 51 | 52 | /// 53 | /// TCP通信时客户端连入事件参数 54 | /// 55 | public class TCPClientConnectedEventArgs : EventArgs 56 | { 57 | /// 58 | /// 新连入的终端 59 | /// 60 | public TCPEndPoint End 61 | { 62 | get; 63 | set; 64 | } 65 | /// 66 | /// 连入时间 67 | /// 68 | public DateTime Time 69 | { 70 | get; 71 | set; 72 | } 73 | } 74 | /// 75 | /// 表示处理客户端连入服务器这一事件的方法 76 | /// 77 | /// 激发该事件的服务器(或客户端)ID 78 | /// 消息参数 79 | public delegate void TCPClientConnectedEventHandler(string csID, TCPClientConnectedEventArgs args); 80 | 81 | /// 82 | /// TCP通信时客户端断开事件参数 83 | /// 84 | public class TCPClientDisConnectedEventArgs : EventArgs 85 | { 86 | /// 87 | /// 断开服务器的终端(已经失效) 88 | /// 89 | public TCPEndPoint End 90 | { 91 | get; 92 | set; 93 | } 94 | /// 95 | /// 断开时间 96 | /// 97 | public DateTime Time 98 | { 99 | get; 100 | set; 101 | } 102 | } 103 | /// 104 | /// 表示处理客户端断开服务器这一事件的方法 105 | /// 106 | /// 激发该事件的服务器(或客户端)ID 107 | /// 消息参数 108 | public delegate void TCPClientDisConnectedEventHandler(string csID,TCPClientDisConnectedEventArgs args); 109 | 110 | /// 111 | /// 表示处理在心跳检测时发现断线这一事件的方法 112 | /// 113 | /// 激发该事件的服务器(或客户端)ID 114 | /// 消息参数 115 | public delegate void TCPClientDisConnected4PulseEventHandler(string csID, int uid); 116 | } 117 | -------------------------------------------------------------------------------- /TJSYXY.Communication/TJSYXY.Communication.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Debug 5 | AnyCPU 6 | 8.0.30703 7 | 2.0 8 | {F2B5C19C-218D-48E0-9BA1-32673F1352B7} 9 | Library 10 | Properties 11 | TJSYXY.Communication 12 | TJSYXY.Communication 13 | v4.0 14 | 512 15 | 16 | 17 | 18 | true 19 | full 20 | false 21 | bin\Debug\ 22 | DEBUG;TRACE 23 | prompt 24 | 4 25 | bin\Debug\TJSYXY.Communication.XML 26 | 27 | 28 | pdbonly 29 | true 30 | bin\Release\ 31 | TRACE 32 | prompt 33 | 4 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 64 | -------------------------------------------------------------------------------- /TJSYXY.Communication/UDP/UDPClient.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Net.Sockets; 5 | using System.Net; 6 | using System.IO; 7 | 8 | namespace TJSYXY.Communication.UDP 9 | { 10 | /// 11 | /// 说明: 12 | /// UDP通信客户端 13 | /// 信息: 14 | /// 周智 2015.07.20 15 | /// 16 | class UDPClient 17 | { 18 | private Socket _socket; //客户端socket 19 | private string _client_id; //客户端ID 20 | 21 | EndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0); //远程终端信息 22 | 23 | byte[] _buffer4recv = new byte[1024 * 64]; //数据接收系统缓冲区 24 | 25 | /// 26 | /// 客户端工作状态 27 | /// 28 | public bool Runing 29 | { 30 | get; 31 | set; 32 | } 33 | 34 | private static Dictionary _udpClients; 35 | /// 36 | /// 客户端列表 37 | /// 38 | public static Dictionary UDPClients 39 | { 40 | get 41 | { 42 | if (_udpClients == null) 43 | { 44 | _udpClients = new Dictionary(); 45 | } 46 | return _udpClients; 47 | } 48 | } 49 | /// 50 | /// 构造方法 51 | /// 52 | /// 客户端ID 53 | public UDPClient(string client_id) 54 | { 55 | _client_id = client_id; 56 | } 57 | /// 58 | /// 开启UDP监听 59 | /// 60 | /// 监听端口号 61 | public void Start(int port) 62 | { 63 | if (!Runing) 64 | { 65 | if (_socket == null) 66 | { 67 | _socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); 68 | } 69 | string ip = Dns.GetHostByName(Dns.GetHostName()).AddressList[0].ToString(); 70 | _socket.Bind(new IPEndPoint(IPAddress.Parse(ip), port)); 71 | _socket.BeginReceiveFrom(_buffer4recv, 0, 1024 * 64, SocketFlags.None, ref remoteEndPoint, new AsyncCallback(OnReceive), remoteEndPoint); 72 | Runing = true; 73 | } 74 | } 75 | /// 76 | /// 数据接收回调方法 77 | /// 78 | /// 回调参数 79 | private void OnReceive(IAsyncResult ar) 80 | { 81 | try 82 | { 83 | int real_recv = _socket.EndReceiveFrom(ar, ref remoteEndPoint); 84 | if (real_recv >= 1) 85 | { 86 | if (UDPMessageReceived != null) 87 | { 88 | UDPMessageReceivedEventArgs args = new UDPMessageReceivedEventArgs(); 89 | args.Msg = (Msg)_buffer4recv[0]; 90 | args.RemoteIP = (remoteEndPoint as IPEndPoint).Address.ToString(); 91 | args.RemotePort = (remoteEndPoint as IPEndPoint).Port; 92 | args.Time = DateTime.Now; 93 | args.Data = new byte[real_recv - 1]; 94 | Buffer.BlockCopy(_buffer4recv, 1, args.Data, 0, real_recv - 1); 95 | UDPMessageReceived(_client_id, args); 96 | } 97 | } 98 | _socket.BeginReceiveFrom(_buffer4recv, 0, 1024 * 64, SocketFlags.None, ref remoteEndPoint, new AsyncCallback(OnReceive), remoteEndPoint); 99 | } 100 | catch 101 | { 102 | 103 | } 104 | } 105 | /// 106 | /// 接收到消息时激发该事件 107 | /// 108 | public event UDPMessageReceivedEventHandler UDPMessageReceived; 109 | /// 110 | /// 同步发送数据 111 | /// 112 | /// 消息类型 113 | /// 数据正文 114 | /// 远程IP 115 | /// 远程端口 116 | public void SendTo(Msg msg, byte[] data,string remoteIP, int remotePort) 117 | { 118 | byte[] buffer2send = new byte[1 + data.Length]; // 1 + data 119 | BinaryWriter sWriter = new BinaryWriter(new MemoryStream(buffer2send)); 120 | 121 | sWriter.Write((byte)msg); 122 | sWriter.Write(data); 123 | sWriter.Close(); 124 | 125 | _socket.SendTo(buffer2send, new IPEndPoint(IPAddress.Parse(remoteIP), remotePort)); //同步发送数据 126 | } 127 | /// 128 | /// 停止监听端口 129 | /// 130 | public void Stop() 131 | { 132 | if (Runing) 133 | { 134 | _socket.Close(); 135 | _socket = null; 136 | Runing = false; 137 | } 138 | } 139 | } 140 | } 141 | -------------------------------------------------------------------------------- /TJSYXY.Communication/UDP/UDPClientManager.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace TJSYXY.Communication.UDP 6 | { 7 | /// 8 | /// 说明: 9 | /// UDP客户端的代理 10 | /// 信息: 11 | /// 周智 2015.07.20 12 | /// 13 | public class UDPClientManager 14 | { 15 | private string _client_id; //要代理的客户端ID 16 | 17 | /// 18 | /// 构造方法 19 | /// 20 | /// 要代理的客户端ID,若不存在,则使用该client_id创建 21 | public UDPClientManager(string client_id) 22 | { 23 | _client_id = client_id; 24 | if (!UDPClient.UDPClients.ContainsKey(_client_id)) 25 | { 26 | UDPClient.UDPClients.Add(_client_id, new UDPClient(_client_id)); 27 | } 28 | } 29 | 30 | /// 31 | /// 开始监听 32 | /// 33 | /// 监听端口号 34 | public void Start(int port) 35 | { 36 | UDPClient.UDPClients[_client_id].Start(port); 37 | } 38 | /// 39 | /// 接收到消息时激发该事件 40 | /// 41 | public event UDPMessageReceivedEventHandler UDPMessageReceived 42 | { 43 | add 44 | { 45 | UDPClient.UDPClients[_client_id].UDPMessageReceived += value; 46 | } 47 | remove 48 | { 49 | UDPClient.UDPClients[_client_id].UDPMessageReceived -= value; 50 | } 51 | } 52 | /// 53 | /// 检查客户端是否存在 54 | /// 55 | /// 要检查的客户端ID 56 | /// 57 | public static bool ClientExist(string client_id) 58 | { 59 | return UDPClient.UDPClients.ContainsKey(client_id); 60 | } 61 | /// 62 | /// 同步发送数据 63 | /// 64 | /// 消息类型 65 | /// 数据正文 66 | /// 远程IP 67 | /// 远程端口 68 | public void SendTo(Msg msg, byte[] data, string remoteIP, int remotePort) 69 | { 70 | UDPClient.UDPClients[_client_id].SendTo(msg, data, remoteIP, remotePort); 71 | } 72 | /// 73 | /// 客户端端口监听状态 74 | /// 75 | public bool Runing 76 | { 77 | get 78 | { 79 | return UDPClient.UDPClients[_client_id].Runing; 80 | } 81 | } 82 | /// 83 | /// 停止监听端口 84 | /// 85 | public void Stop() 86 | { 87 | UDPClient.UDPClients[_client_id].Stop(); 88 | } 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /TJSYXY.Communication/UDP/UDPs.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | 6 | namespace TJSYXY.Communication.UDP 7 | { 8 | /// 9 | /// UDP消息参数 10 | /// 11 | public class UDPMessageReceivedEventArgs : EventArgs 12 | { 13 | /// 14 | /// 消息类型 15 | /// 16 | public Msg Msg 17 | { 18 | get; 19 | set; 20 | } 21 | /// 22 | /// 消息数据 23 | /// 24 | public byte[] Data 25 | { 26 | get; 27 | set; 28 | } 29 | /// 30 | /// 远程IP 31 | /// 32 | public string RemoteIP 33 | { 34 | set; 35 | get; 36 | } 37 | /// 38 | /// 远程端口 39 | /// 40 | public int RemotePort 41 | { 42 | set; 43 | get; 44 | } 45 | /// 46 | /// 消息接收时间 47 | /// 48 | public DateTime Time 49 | { 50 | set; 51 | get; 52 | } 53 | } 54 | /// 55 | /// 表示处理UDP消息的方法 56 | /// 57 | /// 激发该事件的客户端ID 58 | /// 消息参数 59 | public delegate void UDPMessageReceivedEventHandler(string csID, UDPMessageReceivedEventArgs args); 60 | } 61 | -------------------------------------------------------------------------------- /TJSYXY.Communication/ZMessage.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace TJSYXY.Communication 6 | { 7 | /// 8 | /// 说明: 9 | /// 消息数据包,TCP通信中代表一个完整的消息 10 | /// 信息: 11 | /// 周智 2015.07.20 12 | /// 13 | class ZMessage 14 | { 15 | public byte head; //消息头 16 | public int length; //消息体长度 17 | public byte[] content; //消息体 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /TJSYXY.Communication/ZMessageStream.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.IO; 5 | 6 | namespace TJSYXY.Communication 7 | { 8 | /// 9 | /// 说明: 10 | /// 消息缓冲区,TCP通信中确保能接收到完整的消息包 11 | /// 信息: 12 | /// 周智 2015.07.20 13 | /// 14 | class ZMessageStream 15 | { 16 | private byte[] buffer; 17 | private int length; 18 | private int capacity; 19 | 20 | /// 21 | /// 构造方法 22 | /// 23 | public ZMessageStream() 24 | { 25 | buffer = new byte[0]; 26 | length = 0; 27 | capacity = 0; 28 | } 29 | 30 | 31 | /// 32 | /// 从缓冲区中读初一条完整消息 33 | /// 34 | /// 读出的完整消息 35 | /// 如果为true,读取了完整消息 36 | public bool ReadMessage(out ZMessage msg) //从流中读取完整ZMessage对象 37 | { 38 | ZMessage temp = new ZMessage(); 39 | if (length >= 5) 40 | { 41 | MemoryStream stream = new MemoryStream(buffer); 42 | BinaryReader reader = new BinaryReader(stream); 43 | 44 | temp.head = reader.ReadByte(); 45 | temp.length = reader.ReadInt32(); 46 | 47 | if (temp.length <= (length - 5)) 48 | { 49 | temp.content = reader.ReadBytes(temp.length); 50 | reader.Close(); 51 | Remove(temp.length + 5); 52 | msg = temp; 53 | return true; 54 | } 55 | else 56 | { 57 | msg = null; 58 | return false; 59 | } 60 | 61 | } 62 | else 63 | { 64 | msg = null; 65 | return false; 66 | } 67 | } 68 | 69 | 70 | /// 71 | /// 移出缓冲区 72 | /// 73 | /// 要移出缓冲区的字节数 74 | public void Remove(int count) 75 | { 76 | if (count <= length) 77 | { 78 | byte[] b = new byte[length - count]; 79 | Buffer.BlockCopy(buffer, count, b, 0, length - count); 80 | length = capacity = length - count; 81 | buffer = b; 82 | } 83 | else 84 | { 85 | buffer = new byte[0]; 86 | length = capacity = 0; 87 | } 88 | } 89 | 90 | 91 | /// 92 | /// 将字节流写入缓冲区 93 | /// 94 | /// 要写入缓冲区的字节流 95 | /// 写入字节流的开始位置 96 | /// 写入字节大小 97 | public void Write(byte[] bufferEx, int offset, int count) 98 | { 99 | if (count > bufferEx.Length - offset) 100 | { 101 | count = bufferEx.Length - offset; 102 | } 103 | EnsureCapacity(length + count);//再写入之前,判断容量大小 104 | 105 | Buffer.BlockCopy(bufferEx, offset, buffer, length, count); 106 | length += count; 107 | 108 | } 109 | 110 | 111 | /// 112 | /// 确保容量足够大 113 | /// 114 | /// 115 | public void EnsureCapacity(int count) 116 | { 117 | if (count <= capacity) 118 | { 119 | return; 120 | } 121 | if (count < 2 * capacity) 122 | { 123 | count = 2 * capacity; 124 | } 125 | 126 | byte[] bufferEx = new byte[count]; 127 | capacity = count; 128 | Buffer.BlockCopy(buffer, 0, bufferEx, 0, length); 129 | buffer = bufferEx; 130 | } 131 | } 132 | } 133 | -------------------------------------------------------------------------------- /UDPClient/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Windows.Forms; 5 | 6 | namespace UDPClient 7 | { 8 | static class Program 9 | { 10 | /// 11 | /// The main entry point for the application. 12 | /// 13 | [STAThread] 14 | static void Main() 15 | { 16 | Application.EnableVisualStyles(); 17 | Application.SetCompatibleTextRenderingDefault(false); 18 | Application.Run(new frmCreateUDPClient()); 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /UDPClient/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("UDPClient")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("UDPClient")] 13 | [assembly: AssemblyCopyright("Copyright © 2015")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("e2f19618-ebce-4515-96e0-b95c12d2dec4")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /UDPClient/Properties/Resources.Designer.cs: -------------------------------------------------------------------------------- 1 | //------------------------------------------------------------------------------ 2 | // 3 | // This code was generated by a tool. 4 | // Runtime Version:4.0.30319.18444 5 | // 6 | // Changes to this file may cause incorrect behavior and will be lost if 7 | // the code is regenerated. 8 | // 9 | //------------------------------------------------------------------------------ 10 | 11 | namespace UDPClient.Properties 12 | { 13 | 14 | 15 | /// 16 | /// A strongly-typed resource class, for looking up localized strings, etc. 17 | /// 18 | // This class was auto-generated by the StronglyTypedResourceBuilder 19 | // class via a tool like ResGen or Visual Studio. 20 | // To add or remove a member, edit your .ResX file then rerun ResGen 21 | // with the /str option, or rebuild your VS project. 22 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] 23 | [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] 24 | [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] 25 | internal class Resources 26 | { 27 | 28 | private static global::System.Resources.ResourceManager resourceMan; 29 | 30 | private static global::System.Globalization.CultureInfo resourceCulture; 31 | 32 | [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] 33 | internal Resources() 34 | { 35 | } 36 | 37 | /// 38 | /// Returns the cached ResourceManager instance used by this class. 39 | /// 40 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] 41 | internal static global::System.Resources.ResourceManager ResourceManager 42 | { 43 | get 44 | { 45 | if ((resourceMan == null)) 46 | { 47 | global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("UDPClient.Properties.Resources", typeof(Resources).Assembly); 48 | resourceMan = temp; 49 | } 50 | return resourceMan; 51 | } 52 | } 53 | 54 | /// 55 | /// Overrides the current thread's CurrentUICulture property for all 56 | /// resource lookups using this strongly typed resource class. 57 | /// 58 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] 59 | internal static global::System.Globalization.CultureInfo Culture 60 | { 61 | get 62 | { 63 | return resourceCulture; 64 | } 65 | set 66 | { 67 | resourceCulture = value; 68 | } 69 | } 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /UDPClient/Properties/Resources.resx: -------------------------------------------------------------------------------- 1 |  2 | 3 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | text/microsoft-resx 107 | 108 | 109 | 2.0 110 | 111 | 112 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 113 | 114 | 115 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 116 | 117 | -------------------------------------------------------------------------------- /UDPClient/Properties/Settings.Designer.cs: -------------------------------------------------------------------------------- 1 | //------------------------------------------------------------------------------ 2 | // 3 | // This code was generated by a tool. 4 | // Runtime Version:4.0.30319.18444 5 | // 6 | // Changes to this file may cause incorrect behavior and will be lost if 7 | // the code is regenerated. 8 | // 9 | //------------------------------------------------------------------------------ 10 | 11 | namespace UDPClient.Properties 12 | { 13 | 14 | 15 | [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] 16 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "10.0.0.0")] 17 | internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase 18 | { 19 | 20 | private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); 21 | 22 | public static Settings Default 23 | { 24 | get 25 | { 26 | return defaultInstance; 27 | } 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /UDPClient/Properties/Settings.settings: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /UDPClient/UDPClient.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Debug 5 | x86 6 | 8.0.30703 7 | 2.0 8 | {07A276C5-E93D-4F7E-9889-7FC1EAEFA85F} 9 | WinExe 10 | Properties 11 | UDPClient 12 | UDPClient 13 | v4.0 14 | Client 15 | 512 16 | 17 | 18 | x86 19 | true 20 | full 21 | false 22 | bin\Debug\ 23 | DEBUG;TRACE 24 | prompt 25 | 4 26 | 27 | 28 | x86 29 | pdbonly 30 | true 31 | bin\Release\ 32 | TRACE 33 | prompt 34 | 4 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | Form 51 | 52 | 53 | frmCreateUDPClient.cs 54 | 55 | 56 | 57 | 58 | Form 59 | 60 | 61 | frmUDPClient.cs 62 | 63 | 64 | frmCreateUDPClient.cs 65 | 66 | 67 | ResXFileCodeGenerator 68 | Resources.Designer.cs 69 | Designer 70 | 71 | 72 | True 73 | Resources.resx 74 | 75 | 76 | frmUDPClient.cs 77 | 78 | 79 | SettingsSingleFileGenerator 80 | Settings.Designer.cs 81 | 82 | 83 | True 84 | Settings.settings 85 | True 86 | 87 | 88 | 89 | 90 | {F2B5C19C-218D-48E0-9BA1-32673F1352B7} 91 | TJSYXY.Communication 92 | 93 | 94 | 95 | 102 | -------------------------------------------------------------------------------- /UDPClient/frmCreateUDPClient.Designer.cs: -------------------------------------------------------------------------------- 1 | namespace UDPClient 2 | { 3 | partial class frmCreateUDPClient 4 | { 5 | /// 6 | /// Required designer variable. 7 | /// 8 | private System.ComponentModel.IContainer components = null; 9 | 10 | /// 11 | /// Clean up any resources being used. 12 | /// 13 | /// true if managed resources should be disposed; otherwise, false. 14 | protected override void Dispose(bool disposing) 15 | { 16 | if (disposing && (components != null)) 17 | { 18 | components.Dispose(); 19 | } 20 | base.Dispose(disposing); 21 | } 22 | 23 | #region Windows Form Designer generated code 24 | 25 | /// 26 | /// Required method for Designer support - do not modify 27 | /// the contents of this method with the code editor. 28 | /// 29 | private void InitializeComponent() 30 | { 31 | this.textBox2 = new System.Windows.Forms.TextBox(); 32 | this.label2 = new System.Windows.Forms.Label(); 33 | this.textBox1 = new System.Windows.Forms.TextBox(); 34 | this.label1 = new System.Windows.Forms.Label(); 35 | this.button1 = new System.Windows.Forms.Button(); 36 | this.SuspendLayout(); 37 | // 38 | // textBox2 39 | // 40 | this.textBox2.Location = new System.Drawing.Point(36, 79); 41 | this.textBox2.Name = "textBox2"; 42 | this.textBox2.Size = new System.Drawing.Size(176, 21); 43 | this.textBox2.TabIndex = 8; 44 | // 45 | // label2 46 | // 47 | this.label2.AutoSize = true; 48 | this.label2.Location = new System.Drawing.Point(35, 64); 49 | this.label2.Name = "label2"; 50 | this.label2.Size = new System.Drawing.Size(83, 12); 51 | this.label2.TabIndex = 7; 52 | this.label2.Text = "UDP客户端名称"; 53 | // 54 | // textBox1 55 | // 56 | this.textBox1.Location = new System.Drawing.Point(35, 34); 57 | this.textBox1.Name = "textBox1"; 58 | this.textBox1.Size = new System.Drawing.Size(176, 21); 59 | this.textBox1.TabIndex = 6; 60 | // 61 | // label1 62 | // 63 | this.label1.AutoSize = true; 64 | this.label1.Location = new System.Drawing.Point(34, 19); 65 | this.label1.Name = "label1"; 66 | this.label1.Size = new System.Drawing.Size(65, 12); 67 | this.label1.TabIndex = 5; 68 | this.label1.Text = "侦听端口号"; 69 | // 70 | // button1 71 | // 72 | this.button1.Location = new System.Drawing.Point(125, 123); 73 | this.button1.Name = "button1"; 74 | this.button1.Size = new System.Drawing.Size(85, 21); 75 | this.button1.TabIndex = 9; 76 | this.button1.Text = "创建"; 77 | this.button1.UseVisualStyleBackColor = true; 78 | this.button1.Click += new System.EventHandler(this.button1_Click); 79 | // 80 | // frmCreateUDPClient 81 | // 82 | this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); 83 | this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; 84 | this.ClientSize = new System.Drawing.Size(258, 169); 85 | this.ControlBox = false; 86 | this.Controls.Add(this.button1); 87 | this.Controls.Add(this.textBox2); 88 | this.Controls.Add(this.label2); 89 | this.Controls.Add(this.textBox1); 90 | this.Controls.Add(this.label1); 91 | this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow; 92 | this.Name = "frmCreateUDPClient"; 93 | this.Text = "CreateUDPClient"; 94 | this.ResumeLayout(false); 95 | this.PerformLayout(); 96 | 97 | } 98 | 99 | #endregion 100 | 101 | private System.Windows.Forms.TextBox textBox2; 102 | private System.Windows.Forms.Label label2; 103 | private System.Windows.Forms.TextBox textBox1; 104 | private System.Windows.Forms.Label label1; 105 | private System.Windows.Forms.Button button1; 106 | } 107 | } 108 | 109 | -------------------------------------------------------------------------------- /UDPClient/frmCreateUDPClient.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.ComponentModel; 4 | using System.Data; 5 | using System.Drawing; 6 | using System.Linq; 7 | using System.Text; 8 | using System.Windows.Forms; 9 | using TJSYXY.Communication; 10 | using TJSYXY.Communication.UDP; 11 | 12 | namespace UDPClient 13 | { 14 | public partial class frmCreateUDPClient : Form 15 | { 16 | public frmCreateUDPClient() 17 | { 18 | InitializeComponent(); 19 | } 20 | /// 21 | /// 创建客户端 22 | /// 23 | /// 24 | /// 25 | private void button1_Click(object sender, EventArgs e) 26 | { 27 | if (UDPClientManager.ClientExist(textBox2.Text)) 28 | { 29 | MessageBox.Show("客户端已存在!"); 30 | return; 31 | } 32 | UDPClientManager manager = new UDPClientManager(textBox2.Text); 33 | manager.Start(int.Parse(textBox1.Text)); //开启端口监听 34 | 35 | frmUDPClient frmudpclient = new frmUDPClient(textBox2.Text, int.Parse(textBox1.Text)); 36 | frmudpclient.Show(); 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /UDPClient/frmCreateUDPClient.resx: -------------------------------------------------------------------------------- 1 |  2 | 3 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | text/microsoft-resx 110 | 111 | 112 | 2.0 113 | 114 | 115 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 116 | 117 | 118 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 119 | 120 | -------------------------------------------------------------------------------- /UDPClient/frmUDPClient.Designer.cs: -------------------------------------------------------------------------------- 1 | namespace UDPClient 2 | { 3 | partial class frmUDPClient 4 | { 5 | /// 6 | /// Required designer variable. 7 | /// 8 | private System.ComponentModel.IContainer components = null; 9 | 10 | /// 11 | /// Clean up any resources being used. 12 | /// 13 | /// true if managed resources should be disposed; otherwise, false. 14 | protected override void Dispose(bool disposing) 15 | { 16 | if (disposing && (components != null)) 17 | { 18 | components.Dispose(); 19 | } 20 | base.Dispose(disposing); 21 | } 22 | 23 | #region Windows Form Designer generated code 24 | 25 | /// 26 | /// Required method for Designer support - do not modify 27 | /// the contents of this method with the code editor. 28 | /// 29 | private void InitializeComponent() 30 | { 31 | this.groupBox1 = new System.Windows.Forms.GroupBox(); 32 | this.label2 = new System.Windows.Forms.Label(); 33 | this.label1 = new System.Windows.Forms.Label(); 34 | this.textBox5 = new System.Windows.Forms.TextBox(); 35 | this.textBox4 = new System.Windows.Forms.TextBox(); 36 | this.button2 = new System.Windows.Forms.Button(); 37 | this.textBox2 = new System.Windows.Forms.TextBox(); 38 | this.textBox1 = new System.Windows.Forms.TextBox(); 39 | this.button1 = new System.Windows.Forms.Button(); 40 | this.groupBox1.SuspendLayout(); 41 | this.SuspendLayout(); 42 | // 43 | // groupBox1 44 | // 45 | this.groupBox1.Controls.Add(this.label2); 46 | this.groupBox1.Controls.Add(this.label1); 47 | this.groupBox1.Controls.Add(this.textBox5); 48 | this.groupBox1.Controls.Add(this.textBox4); 49 | this.groupBox1.Controls.Add(this.button2); 50 | this.groupBox1.Controls.Add(this.textBox2); 51 | this.groupBox1.Location = new System.Drawing.Point(12, 200); 52 | this.groupBox1.Name = "groupBox1"; 53 | this.groupBox1.Size = new System.Drawing.Size(454, 104); 54 | this.groupBox1.TabIndex = 10; 55 | this.groupBox1.TabStop = false; 56 | this.groupBox1.Text = "发送数据"; 57 | // 58 | // label2 59 | // 60 | this.label2.AutoSize = true; 61 | this.label2.Location = new System.Drawing.Point(302, 23); 62 | this.label2.Name = "label2"; 63 | this.label2.Size = new System.Drawing.Size(29, 12); 64 | this.label2.TabIndex = 10; 65 | this.label2.Text = "Port"; 66 | // 67 | // label1 68 | // 69 | this.label1.AutoSize = true; 70 | this.label1.Location = new System.Drawing.Point(10, 26); 71 | this.label1.Name = "label1"; 72 | this.label1.Size = new System.Drawing.Size(17, 12); 73 | this.label1.TabIndex = 9; 74 | this.label1.Text = "IP"; 75 | // 76 | // textBox5 77 | // 78 | this.textBox5.Location = new System.Drawing.Point(337, 20); 79 | this.textBox5.Name = "textBox5"; 80 | this.textBox5.Size = new System.Drawing.Size(100, 21); 81 | this.textBox5.TabIndex = 8; 82 | // 83 | // textBox4 84 | // 85 | this.textBox4.Location = new System.Drawing.Point(33, 23); 86 | this.textBox4.Name = "textBox4"; 87 | this.textBox4.Size = new System.Drawing.Size(100, 21); 88 | this.textBox4.TabIndex = 7; 89 | // 90 | // button2 91 | // 92 | this.button2.Location = new System.Drawing.Point(348, 52); 93 | this.button2.Name = "button2"; 94 | this.button2.Size = new System.Drawing.Size(89, 23); 95 | this.button2.TabIndex = 1; 96 | this.button2.Text = "发送文本"; 97 | this.button2.UseVisualStyleBackColor = true; 98 | this.button2.Click += new System.EventHandler(this.button2_Click); 99 | // 100 | // textBox2 101 | // 102 | this.textBox2.Location = new System.Drawing.Point(10, 53); 103 | this.textBox2.Name = "textBox2"; 104 | this.textBox2.Size = new System.Drawing.Size(332, 21); 105 | this.textBox2.TabIndex = 0; 106 | // 107 | // textBox1 108 | // 109 | this.textBox1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; 110 | this.textBox1.Location = new System.Drawing.Point(12, 12); 111 | this.textBox1.Multiline = true; 112 | this.textBox1.Name = "textBox1"; 113 | this.textBox1.ReadOnly = true; 114 | this.textBox1.Size = new System.Drawing.Size(454, 176); 115 | this.textBox1.TabIndex = 8; 116 | // 117 | // button1 118 | // 119 | this.button1.Location = new System.Drawing.Point(360, 316); 120 | this.button1.Name = "button1"; 121 | this.button1.Size = new System.Drawing.Size(89, 23); 122 | this.button1.TabIndex = 11; 123 | this.button1.Text = "关闭"; 124 | this.button1.UseVisualStyleBackColor = true; 125 | this.button1.Click += new System.EventHandler(this.button1_Click); 126 | // 127 | // frmUDPClient 128 | // 129 | this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); 130 | this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; 131 | this.ClientSize = new System.Drawing.Size(482, 351); 132 | this.Controls.Add(this.button1); 133 | this.Controls.Add(this.groupBox1); 134 | this.Controls.Add(this.textBox1); 135 | this.Name = "frmUDPClient"; 136 | this.Text = "UDPClient"; 137 | this.Load += new System.EventHandler(this.frmUDPClient_Load); 138 | this.groupBox1.ResumeLayout(false); 139 | this.groupBox1.PerformLayout(); 140 | this.ResumeLayout(false); 141 | this.PerformLayout(); 142 | 143 | } 144 | 145 | #endregion 146 | 147 | private System.Windows.Forms.GroupBox groupBox1; 148 | private System.Windows.Forms.Button button2; 149 | private System.Windows.Forms.TextBox textBox2; 150 | private System.Windows.Forms.TextBox textBox1; 151 | private System.Windows.Forms.Label label1; 152 | private System.Windows.Forms.TextBox textBox5; 153 | private System.Windows.Forms.TextBox textBox4; 154 | private System.Windows.Forms.Label label2; 155 | private System.Windows.Forms.Button button1; 156 | } 157 | } -------------------------------------------------------------------------------- /UDPClient/frmUDPClient.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.ComponentModel; 4 | using System.Data; 5 | using System.Drawing; 6 | using System.Linq; 7 | using System.Text; 8 | using System.Windows.Forms; 9 | using TJSYXY.Communication.UDP; 10 | using TJSYXY.Communication; 11 | 12 | namespace UDPClient 13 | { 14 | public partial class frmUDPClient : Form 15 | { 16 | private string _client_id; 17 | private int _port; 18 | 19 | public frmUDPClient() 20 | { 21 | InitializeComponent(); 22 | } 23 | public frmUDPClient(string client_id, int port) 24 | : this() 25 | { 26 | _client_id = client_id; 27 | _port = port; 28 | } 29 | /// 30 | /// 窗体加载 31 | /// 32 | /// 33 | /// 34 | private void frmUDPClient_Load(object sender, EventArgs e) 35 | { 36 | Text = "UDPClient " + _client_id + ":" + _port; 37 | 38 | //注册事件 39 | UDPClientManager manager = new UDPClientManager(_client_id); 40 | manager.UDPMessageReceived += new UDPMessageReceivedEventHandler(manager_UDPMessageReceived); 41 | } 42 | /// 43 | /// 接受消息 44 | /// 45 | /// 46 | /// 47 | void manager_UDPMessageReceived(string csID, UDPMessageReceivedEventArgs args) 48 | { 49 | this.Invoke((Action)delegate() 50 | { 51 | if (args.Msg == Msg.Zmsg1) 52 | { 53 | textBox1.AppendText(args.Time.ToLongTimeString() + " " + args.RemoteIP + ":" + args.RemotePort + " 发送文本:\n" 54 | + Encoding.Unicode.GetString(args.Data) + "\n"); 55 | } 56 | }); 57 | } 58 | 59 | /// 60 | /// 发送文本 61 | /// 62 | /// 63 | /// 64 | private void button2_Click(object sender, EventArgs e) 65 | { 66 | UDPClientManager manager = new UDPClientManager(_client_id); 67 | manager.SendTo(Msg.Zmsg1, Encoding.Unicode.GetBytes(textBox2.Text), textBox4.Text, int.Parse(textBox5.Text)); 68 | } 69 | /// 70 | /// 关闭 71 | /// 72 | /// 73 | /// 74 | private void button1_Click(object sender, EventArgs e) 75 | { 76 | UDPClientManager manager = new UDPClientManager(_client_id); 77 | manager.Stop(); 78 | } 79 | 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /UDPClient/frmUDPClient.resx: -------------------------------------------------------------------------------- 1 |  2 | 3 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | text/microsoft-resx 110 | 111 | 112 | 2.0 113 | 114 | 115 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 116 | 117 | 118 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 119 | 120 | -------------------------------------------------------------------------------- /file_structure.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sherlockchou86/TJSYXYCommunication/b648c1ebfdead71712477588e363de7e77aef20f/file_structure.png -------------------------------------------------------------------------------- /multiple_tcp_client.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sherlockchou86/TJSYXYCommunication/b648c1ebfdead71712477588e363de7e77aef20f/multiple_tcp_client.png -------------------------------------------------------------------------------- /multiple_tcp_server.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sherlockchou86/TJSYXYCommunication/b648c1ebfdead71712477588e363de7e77aef20f/multiple_tcp_server.png -------------------------------------------------------------------------------- /multiple_udp_client.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sherlockchou86/TJSYXYCommunication/b648c1ebfdead71712477588e363de7e77aef20f/multiple_udp_client.png --------------------------------------------------------------------------------