C#网络通讯

TCP通讯

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.Tasks;

namespace TCP网络程序服务端
{
    class Program
    {
        static void Main(string[] args)
        {
            // 定义端口号
            int port = 888;
            // 创建TCP连接对象
            TcpClient tcpClient;
            // 定义IP地址
            IPAddress[] serverIP = Dns.GetHostAddresses("127.0.0.1");
            // 获得IP地址
            IPAddress localAddress = serverIP[0];
            // 监听套接字
            TcpListener tcpListener = new TcpListener(localAddress, port);
            // 开始接听
            tcpListener.Start();
            // 输出消息
            Console.WriteLine("服务器启动成功,等待用户接入...");
            while (true)
            {
                try
                {
                    // 每接收一个客户端则生成一个TcpClient
                    tcpClient = tcpListener.AcceptTcpClient();
                    // 获取网络数据流
                    NetworkStream networkStream = tcpClient.GetStream();
                    // 定义流数据读取对象
                    BinaryReader reader = new BinaryReader(networkStream);
                    // 定义流数据写入对象
                    BinaryWriter writer = new BinaryWriter(networkStream);
                    while (true)
                    {
                        try
                        {
                            // 接收消息
                            string strReader = reader.ReadString();
                            // 截取客户端消息
                            string[] strReaders = strReader.Split(new char[] { ' ' });
                            // 输出接受的客户端的IP地址
                            Console.WriteLine("有客户端接入,客户IP:" + strReaders[0]);
                            // 输出接受消息
                            Console.WriteLine("来自客户端的消息:" + strReaders[1]);
                            // 定义服务器要写入的消息
                            string strWriter = "我是服务器,我已经收到了您的消息";
                            // 向对方发送消息
                            writer.Write(strWriter);
                        }
                        catch
                        {
                            break;
                        }
                    }
                }
                catch
                {
                    break;
                }
            }

        }
    }
}

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.Tasks;

namespace 网络通讯客户端
{
    class Program
    {
        static void Main(string[] args)
        {
            // 创建一个TcpClient对象,自动分配主机IP地址和端口号
            TcpClient tcpClient = new TcpClient();
            // 连接服务器
            tcpClient.Connect("127.0.0.1", 888);

            if (tcpClient != null) // 判断是否连接成功
            {
                Console.WriteLine("连接服务器成功");
                // 获取数据流
                NetworkStream networkStream = tcpClient.GetStream();
                // 定义流数据读取对象
                BinaryReader reader = new BinaryReader(networkStream);
                // 定义流数据写入对象
                BinaryWriter writer = new BinaryWriter(networkStream);
                // 存储本机IP地址,默认为127.0.0.1
                string localip = "127.0.0.1";
                // 获取所有IP地址
                IPAddress[] ips = Dns.GetHostAddresses(Dns.GetHostName());
                foreach (IPAddress ip in ips)
                {
                    if (!ip.IsIPv6SiteLocal)  // 如果不是IPv6地址
                    {
                        localip = ip.ToString();  // 获取本机IP地址
                    }
                }
                writer.Write(localip + "您好!服务器!我是客户端");
                while (true)
                {
                    try
                    {
                        // 接收服务器发送的消息
                        string strReader = reader.ReadString();
                        if(strReader != null)
                        {
                            // 输出接收的服务器消息
                            Console.WriteLine("来自服务器的消息:" + strReader);
                        }
                    }
                    catch
                    {
                        break;  // 连接过程中出现异常,则退出
                    }
                }
            }
            Console.WriteLine("连接服务器失败");


        }
    }
}

C#网络通讯_ip地址

UDP通讯

UDP的协议通讯的基本模式:

  • 将数据打包(为数据包),然后将数据包发往目的地
  • 接收别人发来的数据包,然后查看数据包

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;

namespace 网络通讯学习
{
    class Program
    {   // 创建UdpClient对象
        static UdpClient udp = new UdpClient();
        static void Main(string[] args)
        {
            // 调用UdpClient对象的Connect方法建立默认远程主机
            udp.Connect("127.0.0.1", 888);
            while (true)
            {
                Thread thread = new Thread(() =>
                {
                    while (true)
                    {
                        try
                        {
                            // 定义一个字节数组,用来存放发送到远程主机的信息
                            Byte[] sendBytes = Encoding.Default.GetBytes("(" + DateTime.Now.ToLongTimeString() + ")晚上8点,413开会");
                            Console.WriteLine("(" + DateTime.Now.ToLongTimeString() + ")晚上8点,413开会");
                            // 调用UdpClient对象的send方法将UDP数据发送到远程主机
                            udp.Send(sendBytes, sendBytes.Length);
                            // 线程休眠2s
                            Thread.Sleep(2000);
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex.Message);
                        }
                    }
                });
                thread.Start();
            }
           
           
        }
    }
}

Client

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

namespace UDP客户端
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            CheckForIllegalCrossThreadCalls = false;
        }
        bool flag = true;
        UdpClient  udp;
        Thread thread;
        private void button1_Click(object sender, EventArgs e)
        {
            // 使用端口号创建UDP连接对象
            udp = new UdpClient(888);
            // 标识接收数据
            flag = true;
            // 创建IPEndPoint对象,用来显示响应主机的标识
            IPEndPoint ipendpoint = new IPEndPoint(IPAddress.Any, 888);
            // 新开线程,执行接收数据操作
            thread = new Thread(() =>
            {
                while (flag)
                {
                    try
                    {
                        // 判断是否有网络数据
                        if (udp.Available <= 0) continue;
                        // 判断连接是否为空
                        if (udp.Client == null) return;
                        // 调用UdpClient对象的Receive方法获得从远程主机返回的UDP数据
                        byte[] bytes = udp.Receive(ref ipendpoint);
                        // 将获得的UDP数据报转为字符串形式
                        string str = Encoding.Default.GetString(bytes);
                        // 显示正在接收的数据
                        textBox2.Text = "正在接收的信息:\n" + str;
                        // 显示所有的接收数据
                        textBox1.Text += "\n" + str;
                    }
                    catch(Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                    Thread.Sleep(2000);
                }
            });
        }

        private void button2_Click(object sender, EventArgs e)
        {
            // 标识不接受数据
            flag = false;
            // 判断线程是否在运行
            if(thread.ThreadState == ThreadState.Running)
            {
                // 终止线程
                thread.Abort();
            }
            // 关闭连接
            udp.Close();

        }
    }
}