TCP UDP基本编程(一)

前言

tcp udp均可以用来网络通信,其基本概念与释义不在此赘述,参考文献如下等,建议多搜一下多看看,以下代码为最最基本的通信方式。
参考文章: https://blog.csdn.net/chuangsun/article/details/67640242。

PS:最基本的同步方法为阻塞线程模式,即在接受消息或者服务端等待连接过程中,主程序在此位置属于阻塞(卡住)状态,只有这一步执行完毕(收到消息或者建立连接)才会进行下一步。所以可以通过死循环来实现循环接受消息。

     udp不存在严格意义上的客户端服务端,只是要确定消息发送的目标主机, 如
            Socket client = socket.Accept();
            int count1 = client.Receive(recv1);

1.socket类

1.1 tcp服务端

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

namespace net
{
    class Program
    {
        static void Main(string[] args)
        {
            string host = "127.0.0.1";
            IPAddress ip = IPAddress.Parse(host);

            //定义侦听端口
            //IPEndPoint ipEnd = new IPEndPoint(IPAddress.Any, 8889);
            IPEndPoint ipEnd = new IPEndPoint(IPAddress.Any, 8889);
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            socket.Bind(ipEnd);
            socket.Listen(10);
            Console.Write("Waiting for a client\r\n");

            //一旦接受连接,创建一个客户端
            Socket client = socket.Accept();
            IPEndPoint ipEndClient = (IPEndPoint)client.RemoteEndPoint;
            Console.Write("已连接:IP: {0}  端口: {1}\r\n", ipEndClient.Address, ipEndClient.Port);

            while(true)
            {
                //接收数据
                byte[] recv1 = new byte[1024];
                int count1 = client.Receive(recv1);
                string str = Encoding.ASCII.GetString(recv1, 0, count1);
                Console.WriteLine("Client:" + Encoding.ASCII.GetString(recv1, 0, count1));

                if(str=="exit")
                {
                    break;
                }

                //发送数据
                string welcome = "Server received:"+ str;
                byte[] data = new byte[1024];
                data = Encoding.ASCII.GetBytes(welcome);
                client.Send(data, data.Length, SocketFlags.None);
            }

            Thread.Sleep(10000);
            Console.Write("\r\n断开连接: {0}", ipEndClient.Address);
            client.Close();
            socket.Close();
            Console.ReadKey();
        }
    }
}

1.2 tcp客户端

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


namespace client
{
    class Program
    {
        static void Main(string[] args)
        {
            //定义主机的IP及端口
            IPAddress ip = IPAddress.Parse("127.0.0.1");
            IPEndPoint ipEnd = new IPEndPoint(ip, 8889);
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            socket.Connect(ipEnd);

            while(true)
            {
                //发送数据
                string msg = Console.ReadLine();
                byte[] msgBytes = new byte[1024];
                msgBytes = Encoding.ASCII.GetBytes(msg);
                socket.Send(msgBytes, msgBytes.Length, SocketFlags.None);

                //接收数据
                byte[] recvMsg = new byte[1024];
                int count = socket.Receive(recvMsg);
                string recvStr = Encoding.ASCII.GetString(recvMsg, 0, count);
                Console.WriteLine(recvStr);

                if(msg=="exit")
                {
                    break;
                }
            }

            Thread.Sleep(10000);
            Console.Write("断开连接"); 
            socket.Shutdown(SocketShutdown.Both);
            socket.Close();
            Console.ReadKey();
        }

    }
}

1.3 udp 服务端

using System;
using System.Text;
using System.Net;
using System.Net.Sockets;

namespace UDP
{
    class Program
    {
        static void Main(string[] args)
        {
            int recv;
            byte[] data = new byte[2048];
       
            IPEndPoint ip = new IPEndPoint(IPAddress.Any, 8001);
            Socket Server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            Server.Bind(ip);
            Console.WriteLine("Server ready!");

            //得到客户机IP
            //IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
            //EndPoint Remote = (EndPoint)(sender);
            //recv = Server.ReceiveFrom(data, ref Remote);
            //Console.Write("Message from "+Remote.ToString()+":");
            //Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));

            客户机连接成功后,发送信息
            //string welcome = "Hello ! ";
            //data = Encoding.ASCII.GetBytes(welcome);
            //Server.SendTo(data, data.Length, SocketFlags.None, Remote);

            while(true)
            {
                //得到客户机IP
                IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
                EndPoint Remote =sender;
                recv = Server.ReceiveFrom(data, ref Remote);
                string recvStr = Encoding.ASCII.GetString(data, 0, recv);
                Console.Write("Message from " + Remote.ToString() + ":");
                Console.WriteLine(recvStr);

                //客户机连接成功后,发送信息
                string welcome = "Server received: "+ recvStr;
                data = Encoding.ASCII.GetBytes(welcome);
                Server.SendTo(data, data.Length, SocketFlags.None, Remote);
            }
            //while (true)
            //{
            //    data = new byte[1024];
            //    //发送接收信息
            //    recv = Server.ReceiveFrom(data, ref Remote);
            //    Console.Write("Message from " + Remote.ToString() + ":");       
            //    Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));

            //    if (Encoding.ASCII.GetString(data, 0, recv) == "exit")
            //        break;

            //    Server.SendTo(data, recv, SocketFlags.None, Remote);
            //}
            //Console.WriteLine("停止");
            Server.Close();
            Console.ReadKey();
        }
    }
}

1.4 udp客户端

using System;
using System.Text;
using System.Net;
using System.Net.Sockets;

namespace UDPClient
{
    class Program
    {
        static void Main(string[] args)
        {
            byte[] data = new byte[1024];         
            IPEndPoint ip = new IPEndPoint(IPAddress.Parse("192.168.8.15"), 8001);
            Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            Console.WriteLine("Client ready:");


            //string welcome = "Server hello!";
            //data = Encoding.ASCII.GetBytes(welcome);
            //server.SendTo(data, data.Length, SocketFlags.None, ip);

            //IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
            //EndPoint Remote = (EndPoint)sender;
            //data = new byte[1024];
            //int recv = server.ReceiveFrom(data, ref Remote);
            //Console.Write("Message from "+Remote.ToString()+":");
            //Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));

            while(true)
            {
                string welcome = Console.ReadLine();
                data = Encoding.ASCII.GetBytes(welcome);
                server.SendTo(data, data.Length, SocketFlags.None, ip);

                IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
                EndPoint Remote = sender;
                data = new byte[1024];
                int recv = server.ReceiveFrom(data, ref Remote);
                Console.Write("Message from " + Remote.ToString() + ":");
                Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
            }
            //while (true)
            //{
            //    input = Console.ReadLine();
            //    server.SendTo(Encoding.ASCII.GetBytes(input), Remote);

            //    if (input == "exit")
            //        break;

            //    data = new byte[1024];
            //    recv = server.ReceiveFrom(data, ref Remote);
            //    stringData = Encoding.ASCII.GetString(data, 0, recv);
            //    Console.Write("Message from " + Remote.ToString() + ":");
            //    Console.WriteLine(stringData);
            //}
            Console.WriteLine("停止");
            server.Close();
            Console.ReadKey();
        }
    }
}

2.TcpClient UdpClient TcpListener类

2.1 tcp服务端

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace TcpServerT
{
    class Program
    {
        static void Main(string[] args)
        {
            //IPAddress IP = IPAddress.Parse("127.0.0.1");
            TcpListener listener = new TcpListener(IPAddress.Any, 1234);
            listener.Start();
            Console.WriteLine("开始监听:");

            //此处也可以采用socket 接收,可以方便进行socket操作
            //Socket s = listener.AcceptSocket();
            TcpClient client = listener.AcceptTcpClient();//接受一个Client  
            Console.WriteLine("已连接:");
            NetworkStream stream = client.GetStream();//获取网络流 
            Console.WriteLine("获取连接流:");
            string receiveString = "";

            while (true)
            {
                byte[] buffer = new byte[client.ReceiveBufferSize];
                stream.Read(buffer, 0, buffer.Length);//读取网络流中的数据 
                receiveString = Encoding.Default.GetString(buffer).Trim('\0');//转换成字符串  
                //StreamReader sr = new StreamReader(stream);
                //receiveString = sr.ReadToEnd();
               
                string sendMsg = "Server received:" + receiveString;
                byte[] sendBytes = Encoding.Default.GetBytes(sendMsg);
                stream.Write(sendBytes, 0, sendBytes.Length);
                stream.Flush();

                Console.WriteLine(receiveString);
                //Console.WriteLine("While++");
                if (receiveString == "exit")
                {
                    stream.Close();//关闭流
                    client.Close();//关闭Client    
                    break;
                }                    
            }
            listener.Stop();
        }
    }
}

2.2 tcp客户端

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace TcpClientT
{
    class Program
    {
        static void Main(string[] args)
        {
            //IPAddress IP = IPAddress.Parse("192.168.8.15");
            //IPEndPoint ip = new IPEndPoint(IP, 1234);
            //TcpClient client = new TcpClient("192.168.8.15",1234);
            IPEndPoint ip = new IPEndPoint(IPAddress.Any, 1234);
            TcpClient client = new TcpClient("127.0.0.1", 1234);
            
            NetworkStream sendStream = client.GetStream();

            while (true)
            {
                string msg = Console.ReadLine();
                Byte[] sendBytes = Encoding.Default.GetBytes(msg);
                sendStream.Write(sendBytes, 0, sendBytes.Length);
                sendStream.Flush();
                //StreamWriter sw = new StreamWriter(sendStream);
                //sw.WriteLine(msg);
                //sw.Flush();

                byte[] buffer = new byte[client.ReceiveBufferSize];
                sendStream.Read(buffer, 0, buffer.Length);//读取网络流中的数据 
                string receiveMsg = Encoding.Default.GetString(buffer).Trim('\0');//转换成字符串  
              
                Console.WriteLine(receiveMsg);

                if (msg == "exit")
                {
                    sendStream.Close();//关闭网络流
                    break;
                }
            }
            client.Close();//关闭客户端  
        }
    }
}

2.3 udp服务端

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

namespace UdpServer
{
    class Program
    {
        static void Main(string[] args)
        {
            UdpClient udpServer = new UdpClient(11000);

            while (true)
            {
                var remoteEP = new IPEndPoint(IPAddress.Any, 11000);
                byte[] recvData = udpServer.Receive(ref remoteEP); // listen on port 11000
                string recvString = Encoding.Default.GetString(recvData);
                Console.Write("Source from" + remoteEP.ToString()+":"+ recvString);

                if(recvString=="exit")
                {
                    break;
                }

                string sendString = "Server received:" + recvString;
                byte[] sendData = Encoding.Default.GetBytes(sendString);
                udpServer.Send(sendData, sendData.Length, remoteEP); // reply back
            }
            udpServer.Close();
        }
    }
}

2.4 udp客户端

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

namespace UdpClientT
{
    class Program
    {
        static void Main(string[] args)
        {
            UdpClient client = new UdpClient();
            IPEndPoint ep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 11000); // endpoint where server is listening
            client.Connect(ep);

            while(true)
            {
                string sendString = Console.ReadLine();
                byte[] sendData = Encoding.Default.GetBytes(sendString);
                client.Send(sendData, sendData.Length);

                byte[] recvData = client.Receive(ref ep);
                string recvString = Encoding.Default.GetString(recvData);
                Console.WriteLine(recvString);

                if (sendString == "exit") break;
            }
            client.Close();       
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值