【C#】C# socket 简单例程一

服务器端伪代码:

            try {
                int port = 2000;
                string host = "127.0.0.1";
                IPAddress ip = IPAddress.Parse(host);
                IPEndPoint ipe = new IPEndPoint(ip, port);
                Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);创建一个Socket类
                s.Bind(ipe);//绑定2000端口
                s.Listen(0);//开始监听
                Console.WriteLine("Wait for connect");
                textBox1.AppendText("Wait for connect\n");
                Socket temp = s.Accept();//为新建连接创建新的Socket。
                Console.WriteLine("Get a connect");
                textBox1.AppendText("Get a connect.\n");
                string recvStr = "";
                byte[] recvBytes = new byte[1024];
                int bytes;
                bytes = temp.Receive(recvBytes, recvBytes.Length, 0);//从客户端接受信息
                recvStr += Encoding.ASCII.GetString(recvBytes, 0, bytes);
                Console.WriteLine("Server Get Message:{0}", recvStr);//把客户端传来的信息显示出来
                textBox1.AppendText("Server Get Message:");
                textBox1.AppendText(recvStr);
                textBox1.AppendText("/n");
                string sendStr = "Ok!Client Send Message Sucessful!";
                byte[] bs = Encoding.ASCII.GetBytes(sendStr);
                temp.Send(bs, bs.Length, 0);//返回客户端成功信息
                temp.Close();
                s.Close();
            }
            catch (ArgumentNullException ee)
            {
                Console.WriteLine("ArgumentNullException: {0}", ee);
                textBox1.AppendText(ee.Message);
            }
            catch (SocketException ee)
            {
                Console.WriteLine("SocketException: {0}", ee);
                textBox1.AppendText(ee.Message);
            }
            Console.WriteLine("Press Enter to Exit");
            Console.ReadLine();

客户端伪代码:

           try
            {
                int port = 2000;
                //string host = "127.0.0.1";
                string host = "192.168.192.54";
                IPAddress ip = IPAddress.Parse(host);
                IPEndPoint ipe = new IPEndPoint(ip, port); //把ip和端口转化成IPEndpoint实例
                Socket c = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                Console.WriteLine("Connecting");
                textBox7.AppendText("Connecting");
                c.Connect(ipe);
                string sendStr = "Hello!This is a socket test";
                byte[] bs = Encoding.ASCII.GetBytes(sendStr);

                Console.WriteLine("Send Message");
                c.Send(bs, bs.Length, 0);//发送测试消息
                    //Thread.Sleep(2000);
                string recvStr = "";
                byte[] recvBytes = new byte[1024];
                int bytes;
                bytes = c.Receive(recvBytes, recvBytes.Length, 0);//从服务器端返回信息
                recvStr += Encoding.ASCII.GetString(recvBytes,0,bytes);
                Console.WriteLine("Client Get Message:{0}", recvStr);//显示服务器返回信息
                c.Close();
            }catch(ArgumentNullException eee)
            {
                Console.WriteLine("ArgumentNullException:{0}", eee);

            }catch(SocketException eee)
            {
                Console.WriteLine("SocketException: {0}", eee);
            }
            Console.WriteLine("Press Enter to Exit");
            textBox7.AppendText("Press Enter to Exit");
            Console.ReadLine();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
#学习的101个经典例子,例子个个经典,涵盖C#的方方面面,带有说详尽的注释 Advanced - Multithreading - How-To Async Calls Advanced - Remoting - How-To TCP Remoting Advanced - Serialization - How-To Serializing Objects Advanced .NET Framework (GDI+) - Animation with GDI+ Advanced .NET Framework (GDI+) - Create a Screensaver with GDI+ Advanced .NET Framework (GDI+) - Use GDI+ to manipulate images Advanced .NET Framework (GDI+) - Working with GDI+ Brushes Advanced .NET Framework (GDI+) - Working with GDI+ Text Advanced .NET Framework (Localization) - Work with Resource Files Advanced .NET Framework (Networking) - Use Sockets Advanced .NET Framework (Threading) -- Thread Pooling Advanced .NET Framework (Windows Services) - Create a Windows Service Advanced .NET Framework - Interacting Windows Service Advanced .NET Framework - Make WIn32 API Calls Data Access - Bind Data in a ComboBox Data Access - Build a Master-Detail Windows Form Data Access - Create an Offline Application Data Access - Custom Data Binding Format Handlers Data Access - Data Entry Form Data Access - How-To Create a Database Data Access - N-Tier Data Form and Data Layer Data Access - Read and Write Images from a Database Data Access - Retreive and Process data with a SQL Data Reader Data Access - Sort and Filter with a DataView Data Access - Use ADO 2.6 Data Access - Use Stored Procedures Data Access - Using Typed Datasets File - How-To File Notifications File - How-To File System Framework - Comparison of DataBinding in Web and Windows Forms Framework - Creating an Enterprise Services Component Framework - How-To Configuration Settings Framework - How-To Environment Settings Framework - How-To MSMQ Framework - How-To Process Viewer Framework - How-To Reflection Framework - How-To Send and Receive Data Framework - How-To Service Manager Framework - How-To Stack Frame Framework - How-To System Events Framework - How-To Work with XML Framework - Key Benefits Framework - Partitioning your application Framework - role based security with Enterprise Services Framework - Scoping, Overloading, Overriding Framework - Understanding the Garbage Collector Framework - Using the COM Port Framework - Using WMI Interop - Automate IE Language - How-To Arrays Language - How-To Build a Custom Collection Class Language - How-To Callbacks Language - How-To DateTime Language - How-To OO Features Language - How-To Strings Language - How-To Try Catch Finally NET Framework - Create and use Trace Listeners NET Framework - How-To Send Mail NET Framework - How-To Use the EventLog NET Framework - How-To Working with GDI+ Pens NET Framework - Read and Write Performance Counters NET Framework - Reading and Writing with a Text File NET Framework - Use Temporary Files NET Framework - Use the Process Class and Shell Functionality NET Framework - Work with Console Applications Security - Create a Login Dialog Box Security - Encrypt and Decrypt Data Security - How-To Role-based Security Security - Use Cryptographic Hash Algorithms VS.NET - Create a VS.NET Add-In Web Development - Data Entry Form Web Development - Exposing a Simple Web Service Web Development - Master-Details Web Form Web Development - Paging through Query Results Web Services - Consume a Web Service WebService - How To Transfer Binary Data Windows Forms - How-To Data Binding with Navigation Windows Forms - How-To System Tray Icon Windows Forms - How-To Validating Textboxes Windows Forms - Associating Help with an Application Windows Forms - Create an Explorer Style Application Windows Forms - How-To Automate Office Windows Forms - How-To Common Dialogs Windows Forms - How-To Data Grid Formatting Windows Forms - How-To DataGrid Sorting and Filtering Windows Forms - How-To Inherited Windows Forms Windows Forms - How-To ListBox and ComboBox Windows Forms - How-To Menus Windows Forms - How-To Top-Level Forms Windows Forms - How-To Use Drag and Drop Windows Forms - How-To XML Comments Windows Forms - Simple Printing Windows Forms - Use Crystal Reports Windows Forms - Use Format Codes to Format Data in Strings Windows Forms - Use Regular Expressions Windows Forms - Use the Clipboard Windows Forms - XP Theme Support Windows Forms -- Owner Drawn Menus Windows Forms- How-To Custom Exceptions WinForms - Dynamic Control Creation

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值