C#控制台应用——利用TCP协议发送,接受数据

客户端发送

C#代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace FTPSend
{
    public class FtpClient
    {

        public static void SendString()
        {
            //要发送的数据
            string str = "hello world";
            //发送的IP地址
            string StrIP = "127.0.0.1";
            //发送的端口号
            string StrPort = "10010";
            //将发送的数据转换成btye格式
            byte[] SendData = Encoding.UTF8.GetBytes(str);
            //IP地址转换
            IPAddress ipadress = IPAddress.Parse(StrIP);
            int port = int.Parse(StrPort);
            //新建TCP客户端
            TcpClient tcpclient = new TcpClient();
            //提供网络访问的基础流的数据
            NetworkStream stream = null;
            try
            {
                //建立连接
                tcpclient.Connect(ipadress, port);
                //返回用于发送和接收数据的 System.Net.Sockets.NetworkStream。
                stream = tcpclient.GetStream();
                //数据写入并发送
                stream.WriteAsync(SendData, 0,str.Length);
                stream.Close();
                tcpclient.Close();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}

服务端接收

c#代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace FTPReceive
{
    class Program
    {
        private static TcpListener server;
        public List<TcpClient> clients = new List<TcpClient>();
        static void Main(string[] args)
        {
            //定义接受的端口号
            int port = 10010;
            //地址解析
            IPAddress iPAddress = IPAddress.Parse("127.0.0.1");
            IPEndPoint ipPOrt = new IPEndPoint(iPAddress, port);
            //开启一个TcpListener用来监听端口
            server = new TcpListener(ipPOrt);
            server.Start();
            Console.Write("启动监听成功");
            server.BeginAcceptTcpClient(new AsyncCallback(DoAcceptTcpclient), server);
            Console.ReadKey();
        }
        private static void DoAcceptTcpclient(IAsyncResult result)
        {
           //获取监听事件,处理客户端请求
            TcpListener listerer = (TcpListener)result.AsyncState;
            TcpClient client = listerer.EndAcceptTcpClient(result);
            List<TcpClient> clients = new List<TcpClient>();
            clients.Add(client);
            Console.WriteLine("客户端建立完成,id{0}",client.Client.RemoteEndPoint.ToString());
            //开一个线程,将处理客户端接受到的数据ParameterizedThreadStart和Start放的都是object
            Thread thread = new Thread(new ParameterizedThreadStart(ReceiveMessageFromClient));
            //开启线程
            thread.Start(client);
            server.BeginAcceptTcpClient(new AsyncCallback(DoAcceptTcpclient), server);
        }
        private static void ReceiveMessageFromClient(object reciveClient)
        {
            byte[] result = new byte[1024];
            //将reciveClient实体装换成TCPClient类
            TcpClient client = reciveClient as TcpClient;
            if (client==null)
            {
                Console.WriteLine("client error");
                return;
            }
            while (true)
            {
                try
                {
                
                    NetworkStream stream = client.GetStream();
                    Console.WriteLine("wait a moment");
                    //读取数据的长度,并放到result结果中
                    int num = stream.Read(result,0,result.Length);
                    if (num != 0)
                    {
                       //将结果转换成str类型
                        string str = Encoding.UTF8.GetString(result, 0, num);
                        Console.WriteLine("数据长度:{0},数据内容:{1}", num, str);
                    }
                    else
                    {
                        Console.WriteLine("客户端关闭");
                        break;
                    }
                }
                catch (Exception ex)
                {

                    throw ex;
                }
            }
        }
    }
}

结果

启动服务端,开始监听

在这里插入图片描述

启动客户端

在这里插入图片描述

数据发送成功在这里插入图片描述

  • 3
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值