C#编程语言基础21

C#网络协议编程

TCP面向连接的可靠协议

服务端:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading;
namespace TcpServer
{
    class Program
    {
        static TcpListener server;
        static void Main(string[] args)
        {
            IPAddress ip = IPAddress.Parse("127.0.0.1");
            server = new TcpListener(ip,8111);
            server.Start();

            Thread th = new Thread(ReciveMsg);
            th.Start();

        }
        static void ReciveMsg()
        {
            try
            {
                while (true)
                {
                    TcpClient client = server.AcceptTcpClient();
                    StreamReader sr = new StreamReader(client.GetStream());
                    string str = sr.ReadLine();
                    Console.WriteLine("收到来自客户端的信息是:" + str);
                }
            }
            catch (Exception)
            {


            }
        }
        static void Send(object o)
        {
            TcpClient client = o as TcpClient;
            StreamWriter sw = new StreamWriter(client.GetStream());
            string str = Console.ReadLine();
            if (str!=null)
            {
                sw.WriteLine(str);
            }
            sw.Flush();
            sw.Close();
        }
    }
}

客户端:

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

namespace TcpClientDemo
{
    class Program
    {
        static TcpClient client;
        static void Main(string[] args)
        {

            try
            {
                while (true)
                {
                    client = new TcpClient("127.0.0.1", 8111);
                    StreamWriter sw = new StreamWriter(client.GetStream());
                    string str = Console.ReadLine();
                    sw.WriteLine(str);
                    sw.Flush();
                    sw.Close();

                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);

            }

            Console.ReadLine();
        }


        static void RecMsg()
        {
            try
            {
                StreamReader sr = new StreamReader(client.GetStream());
                string str = string.Empty;
                if ((str = sr.ReadLine())!=null)
                {
                    Console.WriteLine("来自服务器端的信息是:" + str);
                }

                sr.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }

        }
    }
}

UDP面向无连接的不可靠协议

服务端:

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

namespace UDPServer
{
    class Program
    {
        static void Main(string[] args)
        {
            UdpClient udpRec = new UdpClient(9999);

            try
            {
                while (true)
                {
                    IPEndPoint remoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
                    byte[] recBytes = udpRec.Receive(ref remoteIpEndPoint);
                    string returnData = Encoding.Default.GetString(recBytes);
                    Console.WriteLine("接收到的数据是:" + returnData);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
            finally
            {
                udpRec.Close();
            }
        }
    }
}

客户端:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
namespace UDPClientDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            UdpClient client = new UdpClient("127.0.0.1", 9999);

            try
            {
                while (true)
                {
                    string str = Console.ReadLine();
                    byte[] sendBytes = Encoding.Default.GetBytes(str);
                    client.Send(sendBytes, sendBytes.Length);
                }
            }
            catch (Exception e)
            {

                Console.WriteLine(e);
            }
            finally
            {
                client.Close();
            }
            Console.Read();
        }
    }
}

Socket编程

服务端:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;
using System.Net;
using System.Threading;
namespace NetWork
{
    class Program
    {
        static Socket severSocket;
        static Thread recThread;
        static void Main(string[] args)
        {
            severSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPAddress ip = IPAddress.Parse("127.0.0.1");
            IPEndPoint ipPoint = new IPEndPoint(ip, 9999);

            try
            {
                severSocket.Bind(ipPoint);
                severSocket.Listen(20);
                recThread = new Thread(Listen);
                recThread.Start();

            }
            catch (SocketException se)
            {

                Console.WriteLine(se.Message);
            }
        }


        static void Listen()
        {
            while (true)
            {
                Socket client = severSocket.Accept();
                IPEndPoint ipEndPoint = (IPEndPoint)client.RemoteEndPoint;
                string info = "客户端的ip地址是:"+ipEndPoint.Address + "  客户端的端口号:" + ipEndPoint.Port;

                Thread recThread = new Thread(RecMsg);
                recThread.IsBackground = true;
                recThread.Start(client);
            }
        }

        static void RecMsg(object o)
        {
            try
            {
                byte[] buffer = new byte[1024];
                Socket client = o as Socket;
                IPEndPoint ip = client.RemoteEndPoint as IPEndPoint;

                while (true)
                {
                    int len = client.Receive(buffer);
                    if (len<=0)
                    {
                        return;
                    }
                    string info = Encoding.Default.GetString(buffer,0,len);
                    Console.WriteLine("收到来自客户端"+ip.Address+"  "+ip.Port+"的信息:"+info);

                    //回复收到的消息
                    Thread sendThread = new Thread(Send);
                    sendThread.IsBackground = true;
                    sendThread.Start(client);
                }
            }
            catch (SocketException se)
            {
                Console.WriteLine(se.Message);
            }
        }


        static void Send(object o)
        {
            byte[] buffer = Encoding.Default.GetBytes(Console.ReadLine());
            Socket sc = o as Socket;
            try
            {
                sc.Send(buffer);
            }
            catch (SocketException se)
            {

                Console.WriteLine(se);
            }
        }

        ~Program()
        {
            severSocket.Disconnect(false);
        }

    }
}

客户端:

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

    class Program
    {
        static Socket clientSocket;
        static Thread recThread;
        static void Main(string[] args)
        {
            clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPAddress ipa = IPAddress.Parse("127.0.0.1");
            IPEndPoint ipEndpoint = new IPEndPoint(ipa,9999);
            clientSocket.Connect(ipEndpoint);

            //接收数据
            recThread = new Thread(RecMsg);
            recThread.IsBackground = true;
            recThread.Start();

            //避免 控制台程序启动后
            while (true)
            {
                Send();
            }
        }

        static void RecMsg()
        {
            byte[] buffer = new byte[1024];
            while (true)
            {
                try
                {
                    int len = clientSocket.Receive(buffer);
                    if (len<=0)
                    {
                        return;
                    }
                    string info = Encoding.Default.GetString(buffer,0,len);
                    Console.WriteLine("收到来自服务端的数据:"+info);
                }
                catch (SocketException se)
                {

                    Console.WriteLine(se);
                }
            }
        }

        static void Send()
        {
            byte[] byteArr = Encoding.Default.GetBytes(Console.ReadLine());
            try
            {
                clientSocket.Send(byteArr);
            }
            catch (SocketException se)
            {
                Console.WriteLine(se);
            }
        }


    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值