zoukankan      html  css  js  c++  java
  • Socket套接字

    同步方式:

    Server-服务器端:

    using System;
    using System.IO;
    using System.Net;
    using System.Net.Sockets;
    using System.Text;
    
    namespace Socket套接字
    {
        internal class Program
        {
            private const ushort Port = 50000;
    
            private static void Main()
            {
                var ipAddress = new IPAddress(new byte[] {127, 0, 0, 1}); //IP地址
                var tcpListener = new TcpListener(ipAddress, Port);
                tcpListener.Start();
    
                while (true)
                {
                    try
                    {
                        Console.WriteLine("开始侦听[{0}]端口,等待客户端调用:", Port);
                        TcpClient tcpClient = tcpListener.AcceptTcpClient(); //产生阻塞,等待请求
                        Console.WriteLine("客户端已连接");
                        ProcessClientRequest(tcpClient.GetStream());
                        Console.WriteLine("客户端已断开");
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                        throw;
                    }
                }
            }
    
            private static void ProcessClientRequest(NetworkStream networkStream)
            {
                var streamWriter = new StreamWriter(networkStream);
                const string testFilePath = "C:/text/file.txt";
                if (File.Exists(testFilePath))
                {
                    File.Delete(testFilePath);
                }
                WriteFile(testFilePath, "测试测试");
                var streamReader = new StreamReader(testFilePath, Encoding.Default);
                string stmp = streamReader.ReadLine();
                try
                {
                    while (stmp != null)
                    {
                        Console.WriteLine("Sending:{0}", stmp);
                        streamWriter.WriteLine(stmp);
                        streamWriter.Flush();
                        stmp = streamReader.ReadLine();
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    throw;
                }
                finally
                {
                    streamReader.Close();
                    streamWriter.Close();
                    networkStream.Close();
                }
            }
    
            public static void WriteFile(string filePath, string content)
            {
                try
                {
                    var fs = new FileStream(filePath, FileMode.Create);
                    Encoding encode = Encoding.Default;
                    //获得字节数组
                    byte[] data = encode.GetBytes(content);
                    //开始写入
                    fs.Write(data, 0, data.Length);
                    //清空缓冲区、关闭流
                    fs.Flush();
                    fs.Close();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
        }
    }

    Client-客户端:

    using System;
    using System.IO;
    using System.Net.Sockets;
    
    namespace Socket套接字_同步__客户端
    {
        internal class Program
        {
            private const string Host = "localhost";
            private const ushort Port = 50000;
    
            private static void Main()
            {
                try
                {
                    TcpClient tcpClient = new TcpClient(Host, Port);
                    Console.WriteLine("连接主机:{0}端口:{1}", Host, Port);
                    NetworkStream networkStream = tcpClient.GetStream();
                    var streamReader = new StreamReader(networkStream);
                    try
                    {
                        string stmp = streamReader.ReadLine();
                        while (stmp != null)
                        {
                            Console.WriteLine("收到数据:{0}", stmp);
                            stmp = streamReader.ReadLine();
                        }
                        Console.Read();
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                    finally
                    {
                        streamReader.Close();
                        networkStream.Close();
                    }
                    Console.WriteLine("断开链接");
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
        }
    }

    运行效果:


    异步方式:

    Sever-服务器端:

    using System;
    using System.Net;
    using System.Net.Sockets;
    
    namespace Socket套接字_异步__服务器端
    {
        internal class Program
        {
            private const ushort Port = 50000;
    
            private static void Main()
            {
                var ipAddress = new IPAddress(new byte[] { 127, 0, 0, 1 }); //IP地址
                var tcpListener = new TcpListener(ipAddress, Port);
                tcpListener.Start();
    
                while (true)
                {
                    try
                    {
                        Console.WriteLine("开始侦听[{0}]端口,等待客户端调用:", Port);
                        TcpClient tcpClient = tcpListener.AcceptTcpClient(); //产生阻塞,等待请求
                        // Console.WriteLine("客户端已连接");
                        var clientRequestProcessing = new ClientRequestProcessing(tcpClient.GetStream());
                        clientRequestProcessing.Go();
                        //Console.WriteLine("客户端已断开");
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                        throw;
                    }
                }
            }
        }
    }
    using System;
    using System.Net.Sockets;
    using System.Text;
    using System.Threading;
    
    namespace Socket套接字_异步__服务器端
    {
        public class ClientRequestProcessing
        {
            private const int BufferSize = 512;
            private readonly byte[] _buffer;
            private NetworkStream _networkStream;
    
            public ClientRequestProcessing(NetworkStream networkStream)
            {
                _networkStream = networkStream;
                _buffer = new byte[BufferSize];
            }
    
            public void Go()
            {
                _networkStream.BeginRead(_buffer, 0, _buffer.Length, OnReadDone, null);
            }
    
            private void OnReadDone(IAsyncResult asyncResult)
            {
                int nBytes = _networkStream.EndRead(asyncResult);
                if (nBytes > 0)
                {
                    #region 接收数据
    
                    string sReceived = Encoding.Default.GetString(_buffer, 0, nBytes);
                    Console.WriteLine("异步方式:收到客户端传递数据:{0},共:{1}bytes", sReceived, nBytes);
    
                    #endregion
    
                    Thread.Sleep(2000); //模拟处理数据时间
    
                    #region 返回处理数据
    
                    byte[] sendByte =
                        Encoding.Default.GetBytes("服务器返回收到的数据:" + sReceived + "[" + DateTime.Now.ToString("HH:mm:ss") + "]");
                    _networkStream.BeginWrite(sendByte, 0, sendByte.Length, OnWriteDone, null);
    
                    #endregion
                }
                else
                {
                    Console.WriteLine("异步方式:Client request processed.");
                    _networkStream.Close();
                    _networkStream = null;
                }
            }
    
            private void OnWriteDone(IAsyncResult asyncResult)
            {
                _networkStream.EndWrite(asyncResult);
                Console.WriteLine("异步方式:回传数据给客户端结束.");
                _networkStream.BeginRead(_buffer, 0, _buffer.Length, OnReadDone, null);
            }
        }
    }
    Client-客户端:

    using System;
    using System.IO;
    using System.Net.Sockets;
    using System.Text;
    
    namespace Socket套接字_异步__客户端
    {
        internal class Program
        {
            private const string Host = "localhost";
            private const ushort Port = 50000;
    
            private static void Main()
            {
                try
                {
                    var tcpClient = new TcpClient(Host, Port);
                    Console.WriteLine("连接主机:{0}端口:{1}", Host, Port);
                    NetworkStream networkStream = tcpClient.GetStream();
                    var streamReader = new StreamReader(networkStream, Encoding.Default);
                    var streamWriter = new StreamWriter(networkStream, Encoding.Default);
                    try
                    {
                        const string sSend = "Hi from the Client!";
                        for (int i = 0; i < 3; i++)
                        {
                            #region 发送数据
    
                            Console.WriteLine("客户端->服务器:" + sSend + "[" + DateTime.Now.ToString("HH:mm:ss") + "]");
                            streamWriter.WriteLine(sSend);
                            streamWriter.Flush();
    
                            #endregion
    
                            #region 接收数据
    
                            string sReceived = streamReader.ReadLine();
                            Console.WriteLine("服务器->客户端:" + sReceived + "[" + DateTime.Now.ToString("HH:mm:ss") + "]");
    
                            #endregion
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("异常:" + ex.Message);
                    }
                    finally
                    {
                        streamReader.Close();
                        streamWriter.Close();
                        networkStream.Close();
                    }
                    Console.WriteLine("断开链接");
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
                Console.Read();
            }
        }
    }

    运行效果:




  • 相关阅读:
    战火魔兽CJQ圣印问题
    sublime插件总汇
    js引用类型
    一、vue的数据双向绑定的实现
    渲染机制
    帆布指纹识别
    call、apply与bind在理解
    webpack的世界
    line-height与vertical-align
    'abc' 转换成[a, b, c]一道面试题的思考
  • 原文地址:https://www.cnblogs.com/zhangqs008/p/3059789.html
Copyright © 2011-2022 走看看