C#下使用TCP通讯Demo

本文介绍了一个简单的TCP通信示例,包括服务器端与客户端的实现。服务器监听13000端口,接受来自客户端的消息并以大写形式返回。客户端向服务器发送从'a'到'bye'的信息,并显示服务器的响应。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Demo分成两部分第一部分是Server端 第二部分是Client端

首先是Server端代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Threading;
using System.Net.Sockets;

namespace Server端
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        /*
         * 程序介绍:我要完成一个模拟20000个通讯节点和Server进行通讯的Demo 在测试中服务器端每隔5秒钟向客户端发送请求
         * 请求数据:获取当前时间然后获取当前时间和1990年4月2日的时间差转换成秒然后返回到服务器端
         * 开发时间:2013年8月14日
         * 作者:孙小聪
         * 
         */
        private void Form1_Load(object sender, EventArgs e)
        {
            Thread t = new Thread(new ThreadStart(BackgroundListen));
            t.IsBackground = true;
            t.Start();
        }
        public void BackgroundListen()
        {
            IPAddress ipAddress = IPAddress.Any;
            TcpListener tcpListener = new TcpListener(ipAddress, 13000);
            tcpListener.Start();
            while (true)
            {
                TcpClient tcpClient = tcpListener.AcceptTcpClient();
                MyClient newClient = new MyClient(tcpClient);
                Thread t = new Thread(new ThreadStart(newClient.communicate));
                t.Start();
            }
 
        }
    }
}

需要一个类MyClient

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

namespace Server端
{
    class MyClient
    {
        TcpClient m_tcpClient;
        public MyClient(TcpClient tc)
        {
            m_tcpClient = tc;
        }
        public void communicate()
        {
            NetworkStream ns = m_tcpClient.GetStream();
            int recv;
            string mess;
            while (true)
            {
                byte[] bytes = new byte[1024];
                try
                {
                    if ((recv = ns.Read(bytes, 0, 1024)) == 0)
                    {
                        Console.WriteLine("连接已经断开……");
                        break;
                    }
                }
                catch
                {
                    Console.WriteLine("连接中断……");
                    break;
                }
                mess = System.Text.Encoding.ASCII.GetString(bytes, 0, recv);
                Console.WriteLine(m_tcpClient.Client.AddressFamily.ToString() + "::" + mess);
                bytes = System.Text.Encoding.ASCII.GetBytes(mess.ToUpper());
                try
                {
                    ns.Write(bytes, 0, bytes.Length);
                }
                catch
                {
                    Console.WriteLine("连接已经中断……");
                    break;
                }
            }
            ns.Close();
            m_tcpClient.Close();
        }
    }
}

Client端

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Net.Sockets;
using System.Net;

namespace Client端
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //创建用于通讯的TCPClinet
            TcpClient tcpClient = new TcpClient();
            tcpClient.Connect(IPAddress.Parse("127.0.0.1"), 13000);
            NetworkStream ns = tcpClient.GetStream();
            char b = 'a';
            byte[] bytes = new byte[1024];
            int recv;
            string mess;
            while (true)
            {
                mess = b.ToString(); //将'a'转换成String
                if (b > 3 + 'a')
                    mess = "bye"; //依次发送a  b  c  d bye
                bytes = System.Text.Encoding.ASCII.GetBytes(mess);
                try
                {
                    ns.Write(bytes, 0, bytes.Length);
                }
                catch
                {
                    Console.WriteLine("missing");
                    break;
                }
                bytes = new byte[1024];
                try
                {
                    if ((recv = ns.Read(bytes, 0, 1024)) == 0)
                    {
                        Console.WriteLine("disconnected");
                        break;
                    }
                }
                catch
                {
                    Console.WriteLine("missing");
                    break;
                }
                mess = System.Text.Encoding.ASCII.GetString(bytes, 0, recv);
                MessageBox.Show(mess);
                Thread.Sleep(1000);
                if (b > 3 + 'a')
                    break;
                ++b;
            }
            ns.Close();
            tcpClient.Close();
        }
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值