zoukankan      html  css  js  c++  java
  • C# Socket 入门1

    1.   服务端程序

     1 using System;
     2 using System.Collections.Generic;
     3 using System.Text;
     4 using System.Net.Sockets;
     5 using System.Net;
     6 
     7 namespace ConsoleApplication1
     8 {
     9     class Program
    10     {
    11         static void Main(string[] args)
    12         {
    13             // 1.创建套节字
    14             Socket sListen = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    15 
    16             // 2.填充IP
    17             IPAddress ip = IPAddress.Parse("127.0.0.1");
    18             IPEndPoint ipe = new IPEndPoint(ip, 4321);
    19 
    20             // 3.绑定
    21             sListen.Bind(ipe);
    22 
    23             // 4.监听
    24             sListen.Listen(2);
    25 
    26             // 5.循环接受客户的连接请求
    27             while (true)
    28             {
    29                 Socket clientSocket;
    30                 try
    31                 {
    32                     clientSocket = sListen.Accept();
    33                 }
    34                 catch
    35                 {
    36                     throw;
    37                 }
    38                 // 向客户端发送数据
    39                 clientSocket.Send(Encoding.Unicode.GetBytes("你好呀!!!!"));
    40             }
    41         }
    42 
    43     }
    44 }
    45 

    好完成,,服务端, 

    2 现在请看客户端

     1 using System;
     2 using System.Collections.Generic;
     3 using System.Text;
     4 using System.Net.Sockets;
     5 using System.Net;
     6 
     7 namespace ConsoleApplication2
     8 {
     9     class Program
    10     {
    11         static void Main(string[] args)
    12         {
    13             // 1.创建套节字
    14             Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    15 
    16             // 2.填写远程IP
    17             IPAddress ip = IPAddress.Parse("127.0.0.1");
    18             IPEndPoint ipe = new IPEndPoint(ip, 4321);
    19 
    20             // 3.连接服务器
    21             Console.WriteLine("开始连接服务器....");
    22             s.Connect(ipe);
    23 
    24             // 4.接收数据
    25             byte[] buffer = new byte[1024];
    26             s.Receive(buffer, buffer.Length, SocketFlags.None);
    27             var msg = Encoding.Unicode.GetString(buffer);
    28             Console.WriteLine("接收消息: {0}", msg);
    29 
    30             Console.ReadKey();
    31         }
    32     }
    33 }

    好了, 看看效果 ~~

    简单吗 ~~    

  • 相关阅读:
    php5升级到php7 后对于mysql数据库的关联出现问题的解决方案
    关于js与php互相传值的介绍【转载+自身总结】
    PHP页面间参数传递的四种方法详解
    很久没更新博客了, 明天开始恢复更新。
    SQL 行转列
    oracle 记录被别的用户锁住
    IIS32位,64位模式下切换
    Oracle 分页
    Oracel 提取数字
    Win8 做无线热点
  • 原文地址:https://www.cnblogs.com/LinFx/p/2123685.html
Copyright © 2011-2022 走看看