C#使用TcpListener和TcpClient实现简单通信

Posted diligentyang

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C#使用TcpListener和TcpClient实现简单通信相关的知识,希望对你有一定的参考价值。

本例子为简单使用TcpListener和TcpClient实现通信,含有诸多不足,仅供初学者参考。

server:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Server

    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    
        private TcpListener myListener;
        private TcpClient newClient;
        public BinaryReader br;
        public BinaryWriter bw;

        public MainWindow()
        
            InitializeComponent();
        

        private void button_Click(object sender, RoutedEventArgs e)
        
            Thread myThread = new Thread(ServerA);
            myThread.Start();
        

        private void ServerA() 
            IPAddress ip = IPAddress.Parse("127.0.0.1");//服务器端ip
            myListener = new TcpListener(ip, 7890);//创建TcpListener实例
            myListener.Start();//start
            newClient = myListener.AcceptTcpClient();//等待客户端连接
            label.Dispatcher.Invoke(()=>label.Content = "连接成功");
            while (true)
            
                try
                
                    NetworkStream clientStream = newClient.GetStream();//利用TcpClient对象GetStream方法得到网络流
                    br = new BinaryReader(clientStream);
                    string receive = null;
                    receive = br.ReadString();//读取
                    textBox.Dispatcher.Invoke(() => textBox.Text += receive+"\\r\\n");
                
                catch
                
                    MessageBox.Show("接收失败!");
                
            
        
    //发送消息
        private void send_Click(object sender, RoutedEventArgs e)
        
        //利用TcpClient对象GetStream方法得到网络流
            NetworkStream clientStream = newClient.GetStream();
            bw = new BinaryWriter(clientStream);
            //写入
            bw.Write(message.Text);
            textBox.Text += message.Text + "\\r\\n";
        
    

client:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Client

    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    
        private TcpClient client;
        public BinaryReader br;
        public BinaryWriter bw;
        public MainWindow()
        
            InitializeComponent();
        

        private void button_Click(object sender, RoutedEventArgs e)
        

            Thread myThread = new Thread(ClientA);
            myThread.Start();
        

        private void ClientA() 
        //通过服务器的ip和端口号,创建TcpClient实例
            client = new TcpClient("127.0.0.1", 7890);
            label.Dispatcher.Invoke(()=> label.Content = "与服务器连接成功");
            while (true)
            
                try
                
                    NetworkStream clientStream = client.GetStream();
                    br = new BinaryReader(clientStream);
                    string receive = null;

                    receive = br.ReadString();
                    textBox.Dispatcher.Invoke(() => textBox.Text += receive + "\\r\\n");
                
                catch
                
                    MessageBox.Show("接收失败!");
                
            
        
    //发送消息
        private void send_Click(object sender, RoutedEventArgs e)
        
            NetworkStream clientStream = client.GetStream();
            bw = new BinaryWriter(clientStream);
            bw.Write(message.Text);
            textBox.Text += message.Text + "\\r\\n";
        
    

补充:

textbox多行显示

(1)将TextWrapping设为”Wrap”

(2)将AcceptsReturn设为”True”

(3)将VerticalScrollBarVisibility设置为”Visible”

运行结果:

以上是关于C#使用TcpListener和TcpClient实现简单通信的主要内容,如果未能解决你的问题,请参考以下文章

从服务器(tcplistener)向客户端(tcpclient)发送消息

C# 在客户端和服务器上使用 TcpListener

c#_TcpListener&TcpClient

c#_TcpListener&TcpClient

使用扩展类 tcpClient 连接到 tcpListener

TCPListener和TCPClient之间的通信代码