工作项目总结(八)之TCP/IP通信

来源:互联网 发布:ntfs for mac 15 破解 编辑:程序博客网 时间:2024/06/12 01:53

104、

查找远程端口已建立的连接,读取字符串   // 获取字符串            IPEndPoint endpoint = tcpClient.Client.RemoteEndPoint as IPEndPoint;//创建远程端口监听            TcpListener listener=new TcpListener(endpoint);            const int BufferSize = 8192;              byte[] buffer = new byte[BufferSize];            int bytesRead;          // 读取的字节数            listener.Start();              TcpClient remoteClient = listener.AcceptTcpClient();            NetworkStream streamToClient = remoteClient.GetStream();            MemoryStream msStream = new MemoryStream();            do            {                bytesRead = streamToClient.Read(buffer, 0, BufferSize);                msStream.Write(buffer, 0, bytesRead);            } while (bytesRead > 0);            buffer = msStream.GetBuffer();            string msg = Encoding.Unicode.GetString(buffer);            MSGTXT.AppendText("\r\n数据包:" + msg);


105、

连接远程端口,写入命令 private void button2_Click(object sender, EventArgs e)        {   TcpClient tcpClient = new TcpClient();            tcpClient.Connect("192.168.20.110", 8080);                      // Uses the GetStream public method to return the NetworkStream.            NetworkStream netStream = tcpClient.GetStream();            //写数据命令            if (netStream.CanWrite)            {                //头     源地址    目标地址 控制代码 作用代码 数据长度 校验和                //AA55 C0A8146E C0A8147B    11        00                    //IPAddress ip = IPAddress.Parse("192.168.20.110");                string txt = InputCommand.Text;                Byte[] sendBytes = Encoding.UTF8.GetBytes(txt);                //Byte[] sendBytes = Encoding.UTF8.GetBytes("AA557400110001011F4C");                MSGTXT.AppendText("\r\n发送命令:" + "AA55 1100 0101 1F4C");                netStream.Write(sendBytes, 0, sendBytes.Length);                MSGTXT.AppendText("\r\n长度:" + sendBytes.Length);                Thread.Sleep(3000);            }            else            {                Console.WriteLine("You cannot write data to this stream.");                MSGTXT.AppendText("\r\n无法写入命令:");                tcpClient.Close();                // Closing the tcpClient instance does not close the network stream.                netStream.Close();                return;            }


106、

运行时先运行server 再运行TcppClient 通过客户端发送数据1://创建控制台程序 ServerConsoleusing System;using System.Collections.Generic;using System.Linq;using System.Text; using System.Net;               // 引入这两个命名空间,以下同using System.Net.Sockets;class Server{    static void Main(string[] args)    {        const int BufferSize = 8192;    // 缓存大小,8192Bytes        ConsoleKey key;        Console.WriteLine("Server is running ... ");        IPAddress ip = new IPAddress(new byte[] { 127, 0, 0, 1 });        TcpListener listener = new TcpListener(ip, 8500);        listener.Start();           // 开始侦听        Console.WriteLine("Start Listening ...");        // 获取一个连接,同步方法,在此处中断        TcpClient remoteClient = listener.AcceptTcpClient();        // 打印连接到的客户端信息        Console.WriteLine("Client Connected!{0} <-- {1}",            remoteClient.Client.LocalEndPoint, remoteClient.Client.RemoteEndPoint);        // 获得流        NetworkStream streamToClient = remoteClient.GetStream();        do        {            // 写入buffer中            byte[] buffer = new byte[BufferSize];            int bytesRead;            try            {                lock (streamToClient)                {                    bytesRead = streamToClient.Read(buffer, 0, BufferSize);                }                if (bytesRead == 0) throw new Exception("读取到0字节");                Console.WriteLine("Reading data, {0} bytes ...", bytesRead);                // 获得请求的字符串                string msg = Encoding.Unicode.GetString(buffer, 0, bytesRead);                Console.WriteLine("Received: {0}", msg);                // 转换成大写并发送                msg = msg.ToUpper();                buffer = Encoding.Unicode.GetBytes(msg);                lock (streamToClient)                {                    streamToClient.Write(buffer, 0, buffer.Length);                }                Console.WriteLine("Sent: {0}", msg);            }            catch (Exception ex)            {                Console.WriteLine(ex.Message);                break;            }        } while (true);        streamToClient.Dispose();        remoteClient.Close();        Console.WriteLine("\n\n输入\"Q\"键退出。");        do        {            key = Console.ReadKey(true).Key;        } while (key != ConsoleKey.Q);    }}2://客户端控制台程序TcppClient using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Net;using System.Net.Sockets;namespace TcppClient{      class Client    {        static void Main(string[] args)        {            Console.WriteLine("Client Running ...");            TcpClient client;            ConsoleKey key;            const int BufferSize = 8192;            try            {                client = new TcpClient();                client.Connect("localhost", 8500);      // 与服务器连接            }            catch (Exception ex)            {                Console.WriteLine(ex.Message);                return;            }            // 打印连接到的服务端信息            Console.WriteLine("Server Connected!{0} --> {1}",                client.Client.LocalEndPoint, client.Client.RemoteEndPoint);            NetworkStream streamToServer = client.GetStream();            Console.WriteLine("Menu: S - Send, X - Exit");            do            {                key = Console.ReadKey(true).Key;                if (key == ConsoleKey.S)                {                    // 获取输入的字符串                    Console.Write("Input the message: ");                    string msg = Console.ReadLine();                    byte[] buffer = Encoding.Unicode.GetBytes(msg);     // 获得缓存                    try                    {                        lock (streamToServer)                        {                            streamToServer.Write(buffer, 0, buffer.Length);     // 发往服务器                        }                        Console.WriteLine("Sent: {0}", msg);                        int bytesRead;                        buffer = new byte[BufferSize];                        lock (streamToServer)                        {                            bytesRead = streamToServer.Read(buffer, 0, BufferSize);                        }                        msg = Encoding.Unicode.GetString(buffer, 0, bytesRead);                        Console.WriteLine("Received: {0}", msg);                    }                    catch (Exception ex)                    {                        Console.WriteLine(ex.Message);                        break;                    }                }            } while (key != ConsoleKey.X);            streamToServer.Dispose();            client.Close();            Console.WriteLine("\n\n输入\"Q\"键退出。");            do            {                key = Console.ReadKey(true).Key;            } while (key != ConsoleKey.Q);        }    }}

 

原创粉丝点击