zoukankan      html  css  js  c++  java
  • Socket的简单例子

    服务器端

    using System;using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    using System.Net;
    using System.Net.Sockets;//Socket相关的类
    
    namespace ChatServer
    {
    class Program
    {
    static void Main(string[] args)
    {
    
    //创建服务器上的监听Socket对象,用来监听客户端的连接请求
    Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    //公开一个IP地址和端口号(终结点EndPoint)
    IPEndPoint ep = new IPEndPoint(IPAddress.Any, 18888);
    //将监听Socket对象绑定到终结点
    server.Bind(ep); 
    //开始监听,100指排队的队列长度
    server.Listen(100);
    Console.WriteLine("服务器已经启动了......");
    
    //如果有客户端的连接请求,则接收该连接,自动启动一个数据收发的Socekt对象
    Socket socket = server.Accept();
    
    //接收数据
    byte[] buffer = new byte[1024];
    int length = socket.Receive(buffer);
    Console.WriteLine(System.Text.Encoding.UTF8.GetString(buffer, 0, length));
    
    string info = string.Format("At {0} Server Recive {1} byte info",DateTime.Now.ToString(),length);
    socket.Send(System.Text.Encoding.UTF8.GetBytes(info));
    }
    }
    }

    客户端

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    using System.Net;
    using System.Net.Sockets;
    
    namespace ChatClient
    {
    class Program
    {
    static void Main(string[] args)
    {
    Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    //Connect连接 的终结点是服务器公开的终结点
    client.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"),18888));
    Console.WriteLine("连接成功了");
    
    string info = "hello,I am mwh";
    //发送数据
    client.Send(System.Text.Encoding.UTF8.GetBytes(info));
    
    byte[] buffer = new byte[1024];
    int length = client.Receive(buffer);
    Console.WriteLine(System.Text.Encoding.UTF8.GetString(buffer, 0, length));
    }
    }
    }
  • 相关阅读:
    汇编14:端口
    汇编13:int指令
    整个软件开发的流程
    css grid 布局
    socket粘包处理
    如何做好需求变更管理?——需求变更流程规范
    软件工程需求分析文档模板
    使用layui的form.on绑定select选中事件, form.on()不执行的原因分析
    ID4收藏
    ASP.NET MVC5中View-Controller间数据的传递
  • 原文地址:https://www.cnblogs.com/wnblogs/p/3848761.html
Copyright © 2011-2022 走看看