• 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 }

    好了, 看看效果 ~~

    简单吗 ~~    

  • 相关阅读:
    HDU 4268 multiset
    ACM-线段树
    HDU 5014 异或之和
    HDU 5012 骰子旋转(DFS)
    HDU 5011 NIM博弈
    HDU 5007 字符串匹配
    Android-Context
    Android-视图绘制
    Android-LayoutInflater
    oracle--分页过程demo1
  • 原文地址:https://www.cnblogs.com/LinFx/p/2123685.html
Copyright © 2020-2023  润新知