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));
    }
    }
    }
  • 相关阅读:
    数据库pubs
    当前目录中查找特定类型的文件
    DBHelper,ADO直接操作数据库,扩展DataTable操作数据裤的方法
    行记录次序+等差数列
    面试的通用要求
    zoj_3367Connect them
    hdoj_4198Quick out of the Harbour
    Win32常见异常
    hdoj_1026Ignatius and the Princess I
    移动 II
  • 原文地址:https://www.cnblogs.com/wnblogs/p/3848761.html
Copyright © 2011-2022 走看看