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));
    }
    }
    }
  • 相关阅读:
    分布式数据库拆分表常用的方法
    linux服务器502错误详解【转载】
    全国各城市代码
    Linux下git安装
    linux上访问windows目录
    百度技术总监谈12306高性能海量并发网站架构设计
    Ubuntu 10.04 安装无线网卡驱动。
    晕菜, silverlight !
    linux 软件记录.
    硬盘安装 Ubuntu10.04
  • 原文地址:https://www.cnblogs.com/wnblogs/p/3848761.html
Copyright © 2011-2022 走看看