文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

TCP服务器的C#实现

2023-09-04 05:26

关注

TCP实现类

internal class TcpServer    {        public Socket ServerSocket { get; set; }        public Dictionary<string,Socket> Sockets { get; set; }= new Dictionary<string,Socket>();        public byte[] SendBuffer { get; set; }        public byte[] ReceiveBuffer { get; set; }        ///         /// 创建构造函数        ///         ///         ///         public TcpServer(int sendBufferLength, int receiveBufferLength)        {            SendBuffer = new byte[sendBufferLength];            ReceiveBuffer = new byte[receiveBufferLength];        }        ///         /// 启动服务器        ///         ///         ///         public void Start(string ip, string port)        {            ServerSocket = CreateSocket(ip, port);            CreateThread();        }        ///         /// 服务端向指定客户端发送消息        ///         ///         ///         public void Send(string clientInfo, byte[] data)        {            Socket socket = Sockets[clientInfo];            socket.Send(data);        }        ///         /// 创建服务端Socket        ///         ///         ///         ///         private Socket CreateSocket(string ip, string port)        {            Socket socket=new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);            IPAddress address=IPAddress.Parse(ip);            IPEndPoint endPoint=new IPEndPoint(address, int.Parse(port));            socket.Bind(endPoint);            socket.Listen(20);            return socket;        }        ///         /// 创建监听客户端的线程并启动        ///         private void CreateThread()        {            Thread watchThread = new Thread(WatchConnection);            watchThread.IsBackground = true;            watchThread.Start();        }        ///         /// 监听客户端请求        ///         private void WatchConnection()        {            while (true)            {                Socket clientSocket = null;                try                {                    clientSocket = ServerSocket.Accept();                    IPEndPoint endPoint = (IPEndPoint)clientSocket.RemoteEndPoint;                    string ip= endPoint.Address.ToString();                    string port= endPoint.Port.ToString();                    Sockets.Add(ip + ":" + port, clientSocket);                }                catch (Exception ex)                {                    Console.WriteLine(ex.ToString());                    break;                }                ParameterizedThreadStart pts = new ParameterizedThreadStart(ClientReceiver);                Thread clientThread = new Thread(pts);                clientThread.IsBackground = true;                clientThread.Start(clientSocket);            }        }        ///         ///         ///         ///         private void ClientReceiver(object socket)        {            Socket clientSocket=socket as Socket;            int ReceiveBufferSize = 1 * 1024;            while (true)            {                int receivedLength = 0;                byte[] buffer = new byte[ReceiveBufferSize];                try                {                    List<byte> ls = new List<byte>();                    if (clientSocket != null)                    {                        receivedLength = clientSocket.Receive(buffer);                        if (receivedLength > 0)                        {Buffer.BlockCopy(buffer,0, ReceiveBuffer, 0, receivedLength);string msg = "Receive Success " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");byte[] datas = System.Text.Encoding.UTF8.GetBytes(msg);clientSocket.Send(datas);                        }                    }                }catch(Exception ex)                {                    Console.WriteLine(ex.ToString());                    break;                }            }        }    }

页面布局

<Grid Margin="10">        <Grid.RowDefinitions>            <RowDefinition Height="50"/>            <RowDefinition Height="50"/>            <RowDefinition Height="50"/>            <RowDefinition Height="*"/>            <RowDefinition Height="50"/>            <RowDefinition Height="50"/>        </Grid.RowDefinitions>        <TextBlock Grid.Row="0" Text="配置" VerticalAlignment="Center"/>        <DockPanel Grid.Row="1">            <DockPanel HorizontalAlignment="Left">                <TextBlock Text="地址" VerticalAlignment="Center" Margin="20 0 10 0"/>                <TextBox x:Name="TextBoxIp" Text="" Width="100" Height="36" VerticalContentAlignment="Center"/>                <TextBlock Text="端口" VerticalAlignment="Center" Margin="20 0 10 0"/>                <TextBox x:Name="TextBoxport" Text="" Width="100" Height="36" VerticalContentAlignment="Center"/>                <Button x:Name="ButtonStart" Content="启动" Width="75" Height="36" Margin="20,0,10,0" Click="ButtonStart_Click"/>            </DockPanel>            <DockPanel HorizontalAlignment="Right">                <TextBlock Text="客户端" VerticalAlignment="Center" Margin="20 0 10 0"/>                <ComboBox x:Name="ComboBoxClient" SelectedValuePath="Key" DisplayMemberPath="Key" Width="200" Height="36" Margin="20 0 10 0" SelectionChanged="ComboBoxClient_SelectionChanged"/>            </DockPanel>        </DockPanel>        <TextBlock Grid.Row="2" Text="接收" VerticalAlignment="Center"/>        <TextBox Grid.Row="3" Name="TextBoxReciver" Text=""/>        <TextBlock Grid.Row="4" Text="发送" VerticalAlignment="Center"/>        <StackPanel Grid.Row="5" Orientation="Horizontal">            <TextBox x:Name="TextBoxSender" Text="" Width="650" Height="36"/>            <Button Content="发送" Click="ButtonSend_CLick" Width="75" Height="36" HorizontalAlignment="Right" Margin="10 0 20 0"/>        </StackPanel>    </Grid>

后台代码

TcpServer tcpServer= null;        public MainWindow()        {            InitializeComponent();            tcpServer = new TcpServer(2 * 1024, 2 * 1024);            TextBoxIp.Text = "10.11.10.44";            TextBoxport.Text = "8080";        }        private void ButtonStart_Click(object sender, RoutedEventArgs e)        {            string address = this.TextBoxIp.Text;            string[] arr= address.Split('.');            if (arr.Length == 4)            {                foreach(string item in arr)                {                    int i=int.Parse(item);                    if(i < 0 || i > 255)                    {                        return;                    }                }            }            string port = this.TextBoxport.Text;            int j= int.Parse(port);            if (j < 0)            {                return;            }            ComboBoxClient.ItemsSource = tcpServer.Sockets;            tcpServer.Start(address, port);        }        string currentClient = null;        private void ComboBoxClient_SelectionChanged(object sender, SelectionChangedEventArgs e)        {            //currentClient = ComboBoxClient.SelectedValue.ToString();            ComboBox comboBox = sender as ComboBox;            string str = comboBox.SelectedValue.ToString();            if (tcpServer.Sockets.ContainsKey(str))            {                currentClient = str;            }        }        private void ButtonSend_CLick(object sender, RoutedEventArgs e)        {            if (currentClient != null)            {                string str = TextBoxSender.Text;                byte[] bytes=System.Text.Encoding.UTF8.GetBytes(str);                tcpServer.Send(currentClient,bytes);            }        }

运行结果
在这里插入图片描述

来源地址:https://blog.csdn.net/qq_27474555/article/details/131287696

阅读原文内容投诉

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     813人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     354人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     318人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     435人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     224人已做
    查看

相关文章

发现更多好内容

猜你喜欢

AI推送时光机
位置:首页-资讯-服务器
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯