c# 控制台 socket 实现发送消息-客户端-升级

c# 控制台 socket 实现发送消息-客户端-升级

之前的版本:c# 控制台 socket 实现发送消息-客户端

服务端C# 控制台 socket 实现发送消息-服务端-升级

新增:1、连接端口时要求输入昵称,传给服务器,服务器返回你的参数。
2、禁用了关闭按钮,输入‘exit’退出。
3、接收消息时,会输出发送人的ID,昵称,判断是不是自己发送的消息请添加图片描述

命名空间引用

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.IO;
using System.Runtime.InteropServices;

全局参数配置

static TcpClient client;
        static NetworkStream stream;
        //记录自己的ID
        static int ID = 0;

        // 导入 Windows API 函数以获取控制台窗口句柄和设置窗口属性
        [DllImport("kernel32.dll")]
        public static extern IntPtr GetConsoleWindow();

        [DllImport("user32.dll")]
        public static extern IntPtr GetSystemMenu(IntPtr hWnd, bool bRevert);

        [DllImport("user32.dll")]
        public static extern bool DeleteMenu(IntPtr hMenu, uint uPosition, uint uFlags);

        const int SC_CLOSE = 0xF060;

        const int MF_BYCOMMAND = 0x00000000;

Mian函数


        static void Main(string[] args)
        {
            // 获取当前控制台窗口句柄
            IntPtr consoleWindow = GetConsoleWindow();

            // 获取系统菜单句柄并移除关闭按钮 
            IntPtr systemMenu = GetSystemMenu(consoleWindow,false);
            if (systemMenu != IntPtr.Zero)
            {
                DeleteMenu(systemMenu,SC_CLOSE,MF_BYCOMMAND);
            }

            Console.Write("请输入要连接的服务器IP地址: ");
            string serverIp = Console.ReadLine();

            Console.Write("请输入要连接的服务器端口号: ");
            int port = int.Parse(Console.ReadLine());

            Console.Write("请输入你进入这个端口的名字: ");
            string name = Console.ReadLine();

            client = new TcpClient(serverIp, port);
            Console.WriteLine("已连接到服务器");

            stream = client.GetStream();
            //传入你加入这个端口你的名称
            name += "-portname-";//加上标识
            byte[] bytesToName = Encoding.UTF8.GetBytes(name);
            stream.Write(bytesToName, 0, bytesToName.Length);

            Thread receiveThread = new Thread(ReceiveMessages);
            receiveThread.Start();
            Console.Write("请输入消息(输入'exit'退出程序): ");
            while (true)
            {
                
                string messageToSend = Console.ReadLine();
                //携带自己的ID
                messageToSend += "-ID-:"+ID;
                byte[] bytesToSend = Encoding.UTF8.GetBytes(messageToSend);

                stream.Write(bytesToSend, 0, bytesToSend.Length);

                if (messageToSend == "exit")
                {
                    break;
                }
            }

            client.Close();
        }

ReceiveMessages()方法

        static void ReceiveMessages()
        {
            while (true)
            {
                if (stream.DataAvailable)
                {
                    byte[] buffer = new byte[1024];
                    int bytesRead = stream.Read(buffer, 0, buffer.Length);
                    string dataReceived = Encoding.UTF8.GetString(buffer, 0, bytesRead);
                    //刚开始进来的时候获取返回的ID
                    if(dataReceived.Contains("-yourID-"))
                    {
                        int startIndex = 0; // 子串的起始位置为0
                        int endIndex = dataReceived.IndexOf("-");   // 找到第一个 "-" 的位置

                        if (endIndex != -1)
                        {
                            dataReceived = dataReceived.Substring(startIndex, endIndex);
                        }
                        ID = Convert.ToInt32(dataReceived);
                        continue;
                    }

                    //截取信息
                    string[] parts = dataReceived.Split('-');
                    //string lastPart = parts[parts.Length - 2];
                    //返回的消息
                    string firstPart = parts[0];
                    //发送人的名字
                    string secondPart = parts[2].Substring(1);
                    //发送人的ID
                    string lastPart = parts[4].Substring(1);
                    //退出
                    if (firstPart == "exit" && Convert.ToInt32(lastPart) == ID)
                    {
                        // 通过调用 Environment.Exit 方法来立即终止控制台应用程序
                        Environment.Exit(0); 
                    }
                    Console.WriteLine("");
                    //根据返回的信息判断是不是自己发送的信息
                    if(Convert.ToInt32(lastPart) == ID)
                    {
                        Console.WriteLine($"ID为:{lastPart} - 自己: {firstPart}");
                    }
                    else
                    {
                        Console.WriteLine($"ID为:{lastPart} - {secondPart}: {firstPart}");
                    }
                    Console.WriteLine("请输入消息(输入'exit'退出程序): ");
                }
            }
        }

请添加图片描述

  • 20
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值