zoukankan      html  css  js  c++  java
  • C# socket 简单实现server呈现client发送信息

    server

    -----------------

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Net.Sockets;
    using System.Net;
    using System.Threading;

    namespace ServerSocketDemo
    {
        
    class Program
        {
            
    static IPEndPoint serverEndPoint;
            
    static IPEndPoint clientEndPoint;    
            
    static Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            
    static Socket clientSocket;

     

            
    /// <summary>
            
    /// 设置终结点
            
    /// </summary>
            public static void SetServerEndPoint()
            {
                
    // IPHostEntry hostEntry = new IPHostEntry();
                IPAddress[] ipadddress = Dns.GetHostAddresses(Dns.GetHostName()); //

                Console.WriteLine(
    "server ip :{0}", ipadddress[0].ToString());
                
    //IPAddress.Any
                serverEndPoint = new IPEndPoint(ipadddress[0], 7788);

            }
           
            
    /// <summary>
            
    ///  监听
            
    /// </summary>
            static void SetServerSocketListen()
            {
                
    // 绑定
                serverSocket.Bind(serverEndPoint);
                
    // 监听
                serverSocket.Listen(20);
                Console.WriteLine(
    "开始在{0}:{1}上监听", serverEndPoint.Address.ToString(), serverEndPoint.Port.ToString());

                 
    // 新的客户端socket

                clientSocket 
    = serverSocket.Accept();

                
    // 有新连接创建时 
                clientEndPoint = (IPEndPoint)clientSocket.RemoteEndPoint;
                Console.WriteLine(
    "connect with client:" + clientEndPoint.Address + " at port:" + clientEndPoint.Port);
               
    //先客户端 发送
                string welcome = "welcome !";
                
    byte[] welcomeByte = Encoding.UTF8.GetBytes(welcome);
                clientSocket.Send(welcomeByte);

                ReviceData();
            }

            
    /// <summary>
            
    /// 接收数据
            
    /// </summary>
            
    /// <param name="args"></param>
            static void ReviceData()
            {
                
    /// 循环接收数据
                while (true)
                {
                    
    if (clientSocket != null)
                    {                   
                        
    byte[] data = new byte[1024];
                        
    //将数据 缓存到 data
                        int buffer = clientSocket.Receive(data);
                        
    if (buffer > 0)
                        {
                            
    //  数据不到1024 时使用Encoding.UTF8.GetString(byte[] ) 回接收大片空白
                            string strData = Encoding.UTF8.GetString(data,0,buffer);// 只转换相应的数据大小                   
                            Console.WriteLine("from {0} : {1}", ((IPEndPoint)clientSocket.RemoteEndPoint).Address.ToString(), ((IPEndPoint)clientSocket.RemoteEndPoint).Port.ToString());
                            Console.WriteLine(strData);
     
                            
    //   将数据 返回
                            
    //   client.Send(data, recv, SocketFlags.None);
                            
    //   clientSocket.Send(bytes, buffer, SocketFlags.None);

                        }
                    }
                }
            }
            
            
    static void Main(string[] args)
            {
                SetServerEndPoint();
                Thread serverThrad 
    = new Thread(new ThreadStart(SetServerSocketListen));
                serverThrad.IsBackground 
    = true;
                serverThrad.Start();
                serverThrad.Join();

            }
        }
    }

    client

    ----------


     

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    using System.Threading;
    using System.Net.Sockets;
    using System.Net;

    namespace ClientSocketDemo
    {
        
    class Program
        {
            
    static IPAddress[] ipadress;
         
    //   static IPEndPoint clientEndPoint;
            static IPEndPoint servetEndPoint;
            
    static string info;
            
    static Socket clientSocket;// = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            
    static void send()
            {
                
    try
                {
                    
    // 循环发送
                    while (true)
                    {
                        
    //客户端发送信息
                        info = Console.ReadLine();
                        Byte[] infobyte 
    = Encoding.UTF8.GetBytes(info);
                        clientSocket.Send(infobyte);
                     
                        
    //接收返回的信息
                        
    //byte[] data = new byte[1024];
                        
    //int recv = clientSocket.Receive(data);
                        
    //string stringdata = Encoding.UTF8.GetString(data, 0, recv);                    
                        
    //Console.WriteLine(stringdata);

                    }
                }
                
    finally
                {
                    
                    clientSocket.Shutdown(SocketShutdown.Both);
                    clientSocket.Close();
                }
            }


            
    static void Main(string[] args)
            {
                IPAddress serverIpaddress;
                
    //  服务节点
                IPAddress.TryParse("192.168.1.106"out serverIpaddress);
                servetEndPoint 
    = new IPEndPoint(serverIpaddress, 7788);

                
    ////  客户节点
                //ipadress = Dns.GetHostAddresses(Dns.GetHostName());
                
    //clientEndPoint = new IPEndPoint(ipadress[0], 8877);

                
    // 创建客户端socket
                clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
               
                
    // 连接
                clientSocket.Connect(servetEndPoint);
                
    byte[] data = new byte[1024];
                
    // 将接受的数据缓存到 data
                int recv = clientSocket.Receive(data);
                
    string stringdata = Encoding.ASCII.GetString(data, 0, recv);
                
    // 输出欢迎信息 证明连接上。
                Console.WriteLine(stringdata);


                Thread th 
    = new Thread(new ThreadStart(send));
                th.Start();


            }
        }
    }

     

    自己参照  http:
    //www.cnblogs.com/dooom/archive/2010/09/19/1831165.html 写的. 

    1.   // 连接到server的新客户端socket 

           clientSocket 
    = serverSocket.Accept();

    2.  服务端没有监听的话(serverSocket.Listen(20);),会有 XX积极拒绝连接的提示。

    3.


     

  • 相关阅读:
    react 调用webIm
    css样式问题解决
    学习animejs
    vue,在模块中动态添加dom节点,并监听
    vue 关于solt得用法
    vue-cli 安装过程出现错误
    处理参数中存在多个连续空格,只显示一个空格,复制后搜索不到得问题
    http StatusCode(状态码)
    修改表单小技巧
    关于swiper中包含表单元素的bug
  • 原文地址:https://www.cnblogs.com/dayou123123/p/2073942.html
Copyright © 2011-2022 走看看