.NET Core 2.1 TcpServer Demo

服务器端C#(.net core 2.1)

using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace dotNetSocketServer
{
    class Program
    {
        static void Main(string[] args)
        {
            Int32 port = 13000;
            IPAddress localadd = IPAddress.Any;
            TcpListener server = new TcpListener(localadd, port);
            server.Start();
            Byte[] bytes = new byte[256];
            String data = null;
            TcpClient client=null;
            try
            {
                while (true)
                {
                    Console.WriteLine("等待新的连接...");
                    client = server.AcceptTcpClient();
                    Console.WriteLine("连接成功!");
                    data = null;
                    NetworkStream nstream = client.GetStream();
                    int offset;
                    while ((offset = nstream.Read(bytes, 0, bytes.Length)) != 0)
                    {
                        data = System.Text.Encoding.UTF8.GetString(bytes, 0, offset);
                        Console.WriteLine("收到了:" + data);
                        byte[] msg = System.Text.Encoding.UTF8.GetBytes(data);
                        nstream.Write(msg, 0, msg.Length);
                        Console.WriteLine("发送了:{0}", data);
                    }
                }
            }
            catch (Exception ex)
            {
                client.Close();
                Console.WriteLine(ex.Message);
            }
            Console.WriteLine("服务器已停止.");
            Console.ReadLine();
          
        }
    }
}

客户端(C++ Qt)

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include
#include
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    socket=new QTcpSocket();
    socket->connectToHost(QHostAddress("127.0.0.1"),13000);
   connect(socket,SIGNAL(connected()),this,SLOT(connsucc()));
   connect(socket,SIGNAL(readyRead()),this,SLOT(recv()));
}

MainWindow::~MainWindow()
{
    delete ui;
}
void MainWindow::connsucc()
{
    char d[1024]="你好我是数据ABCabc123...~";
    socket->write(d,strlen(d));
}
void MainWindow::recv()
{
   QString  data=   socket->readAll();
   QMessageBox::about(this,"收到的数据",data);
}

运行:

.NET Core 2.1 TcpServer Demo_第1张图片

.NET Core 2.1 TcpServer Demo_第2张图片

Github示例代码

你可能感兴趣的:(.NET,Core)