C# Socket 例子(控制台程序)

服务器代码

复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;


namespace TCPListener
{
    class Program
    {
        static void Main(string[] args)
        {
            const int BufferSize = 1024;
            Console.WriteLine("Sever is running....");
            IPAddress IP = new IPAddress(new byte[] { 127, 0,0,1 });
            TcpListener lister = new TcpListener(IP,8500);
            lister.Start();

            Console.WriteLine("Start Listering....");
           

           
            TcpClient remoteClient = lister.AcceptTcpClient();
            Console.WriteLine("Client Connected!{0} <-- {1}", remoteClient.Client.LocalEndPoint, remoteClient.Client.RemoteEndPoint);

            NetworkStream streamToClient = remoteClient.GetStream();
            try
            {
                while (true)
                {


                    byte[] buffer = new byte[BufferSize];

                    int bytesRead = streamToClient.Read(buffer, 0, BufferSize);
                    Console.WriteLine("Reading data {0} bytes....", bytesRead);
                    // 获得请求的字符串
                    string msg = Encoding.Unicode.GetString(buffer, 0, bytesRead);

                    Console.WriteLine("Received: {0}", msg);
                    //将字符串转换为大写
                    msg = msg.ToUpper();
                    buffer = Encoding.Unicode.GetBytes(msg);
                    lock (streamToClient) 
                    {
                        streamToClient.Write(buffer, 0, buffer.Length); 
                    }
                    Console.WriteLine("Sent: {0}", msg);
                }
            }
            catch(Exception e) 
            {
                remoteClient.Close();
            }
            //}
            Console.WriteLine("\n\n输入\"Q\"键退出。");
            streamToClient.Dispose();
            remoteClient.Close();

            ConsoleKey Key;
            do
            {
                Key = Console.ReadKey(true).Key;

            } while (Key != ConsoleKey.Q);
          


        }
    }
}
复制代码

客户端代码:

复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;

namespace TCPconnect
{
    class Program
    {
        static void Main(string[] args)
        {
             string msg;
             const int BufferSize = 1024;

            IPAddress SeverIP =  IPAddress.Parse("127.0.0.1");

            Console.WriteLine("TCPClient is running");
            TcpClient Client;
            //for (int i = 0; i <= 2; i++)
            //{
                try
                {
                    Client = new TcpClient();
                    Client.Connect(SeverIP, 8500);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                    return;
                }
                Console.WriteLine("Sever Connected! {0}-->{1}", Client.Client.LocalEndPoint, Client.Client.RemoteEndPoint);

            //}
                Console.WriteLine("请输入发送的内容");
                NetworkStream StreamToSever = Client.GetStream();

                ConsoleKey key;
                Console.WriteLine("Menu: S - Send, X - Exit");

            do{
                 key = Console.ReadKey(true).Key;
                 if (key == ConsoleKey.S)
                 {

                     msg = Console.ReadLine();

                     byte[] buffer = Encoding.Unicode.GetBytes(msg);//获取缓存

                     lock (StreamToSever)
                     {
                         StreamToSever.Write(buffer, 0, buffer.Length);
                     }

                     Console.WriteLine("Sent:{0}", msg);

                     int bytesRead;
                     buffer = new byte[BufferSize];
                     lock (StreamToSever)
                     {
                         bytesRead = StreamToSever.Read(buffer, 0, BufferSize);
                     }
                     msg = Encoding.Unicode.GetString(buffer, 0,bytesRead);
                     Console.WriteLine("Received: {0}", msg);
                 }
            } while (key != ConsoleKey.X);

            Console.WriteLine("\n\n输入\"Q\"键退出。");

            ConsoleKey Key;
            do
            {
                Key = Console.ReadKey(true).Key;

            } while (Key != ConsoleKey.Q);


        }
    }
}
复制代码

 

posted @   dongzhaosheng73  阅读(427)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 通过 API 将Deepseek响应流式内容输出到前端
· AI Agent开发,如何调用三方的API Function,是通过提示词来发起调用的吗
点击右上角即可分享
微信分享提示