socket的Listen和Connect 及 Tcp的TcpListener和TcpClient

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;

//socket listen
private void btn_startlisten_Click(object sender, EventArgs e)
{
    try
    {
        // create the socket
        Socket listenSocket = new Socket(AddressFamily.InterNetwork,
                                         SocketType.Stream,
                                         ProtocolType.Tcp);
        // bind the listening socket to the port           
        IPAddress hostIP = IPAddress.Parse("127.0.0.1");
        int port = 4567;
        //IPAddress hostIP = (Dns.Resolve(IPAddress.Any.ToString())).AddressList[0];           
        IPEndPoint ep = new IPEndPoint(hostIP, port);
        listenSocket.Bind(ep);

        // start listening
        int backlog = 0;
        listenSocket.Listen(backlog);

        while (true)
        {
            if (listenSocket.Poll(-1, SelectMode.SelectRead))
            {
                Socket mySocket = listenSocket.Accept();

                byte[] bytes = new byte[256];
                mySocket.Receive(bytes);
                this.txt_Msg.Text += string.Format(Encoding.UTF8.GetString(bytes) + "/r/n");
                //MessageBox.Show(Encoding.UTF8.GetString(bytes));

                byte[] msg = Encoding.UTF8.GetBytes("This is a test S->C" + DateTime.Now.ToString());
                mySocket.Send(msg);

                mySocket.Shutdown(SocketShutdown.Both);
                mySocket.Close();
            }
        }
        //listenSocket.Close();
    }
    catch (Exception ex)
    {
        this.txt_Msg.Text = ex.ToString();
    }
}

//socket client
private void button1_Click(object sender, EventArgs e)
{
    try
    {
        byte[] msg = Encoding.UTF8.GetBytes("This is a test C->S"+DateTime.Now.ToString());
        byte[] bytes = new byte[256];

        Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        s.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 4567));
        // Blocks until send returns.
        int i = s.Send(msg);
        this.textBox1.Text = string.Format("Sent {0} bytes.", i);

        // Get reply from the server.
        i = s.Receive(bytes);
        this.textBox1.Text = string.Format(Encoding.UTF8.GetString(bytes));

        //释放资源
        s.Close();
    }
    catch (Exception ex)
    {
        this.textBox1.Text = ex.ToString();
    }
}

 

//TcpListener
private void button1_Click(object sender, EventArgs e)
        {
            TcpListener server = null;
            try
            {
                // Set the TcpListener on port 13000.
                Int32 port = 13000;
                IPAddress localAddr = IPAddress.Parse("127.0.0.1");

                // TcpListener server = new TcpListener(port);
                server = new TcpListener(localAddr, port);

                // Start listening for client requests.
                server.Start();

                // Buffer for reading data
                Byte[] bytes = new Byte[256];
                String data = null;
               
                int j = 0;//
                // Enter the listening loop.
                while (j<2)//true
                {
                    j = j + 1;
                    // Perform a blocking call to accept requests.
                    // You could also user server.AcceptSocket() here.
                    TcpClient client = server.AcceptTcpClient();

                    data = null;

                    // Get a stream object for reading and writing
                    NetworkStream stream = client.GetStream();

                    int i;

                    // Loop to receive all the data sent by the client.
                    while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
                    {
                        // Translate data bytes to a ASCII string.
                        data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
                        this.textBox1.Text += DateTime.Now.ToString() + " Received: " + data+"/r/n";

                        // Process the data sent by the client.
                        data = data.ToUpper() + DateTime.Now.ToString();                     

                        byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);

                        // Send back a response.
                        stream.Write(msg, 0, msg.Length);
                        this.textBox1.Text += " Sent back: " + data + "/r/n";
                    }

                    // Shutdown and end connection
                    client.Close();
                }
               
            }
            catch (SocketException ex)
            {
                this.textBox1.Text = ex.ToString();
            }
            finally
            {
                // Stop listening for new clients.
                server.Stop();
            }

        }

//TcpClient
private void button1_Click(object sender, EventArgs e)
{
    try
    {
      
        // Create a TcpClient.
        // Note, for this client to work you need to have a TcpServer
        // connected to the same address as specified by the server, port
        // combination.
        string server = "127.0.0.1";
        Int32 port = 13000;
        TcpClient client = new TcpClient(server, port);

        string message = " test data c->s ";
        // Translate the passed message into ASCII and store it as a Byte array.
        Byte[] data = System.Text.Encoding.ASCII.GetBytes(message);

        // Get a client stream for reading and writing.
        //  Stream stream = client.GetStream();

        NetworkStream stream = client.GetStream();

        // Send the message to the connected TcpServer.
        stream.Write(data, 0, data.Length);

        this.textBox1.Text += DateTime.Now.ToString() + "Sent:" + message + "/r/n";

        // Receive the TcpServer.response.

        // Buffer to store the response bytes.
        data = new Byte[256];

        // String to store the response ASCII representation.
        String responseData = String.Empty;

        // Read the first batch of the TcpServer response bytes.
        Int32 bytes = stream.Read(data, 0, data.Length);
        responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
        this.textBox1.Text += DateTime.Now.ToString() + "Received:" + responseData + "/r/n";
        // Close everything.
        stream.Close();
        client.Close();
    }
    catch (ArgumentNullException ex)
    {
        this.textBox1.Text = ex.ToString();
    }
    catch (SocketException ex)
    {
        this.textBox1.Text = ex.ToString();
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C#中的TcpClientTcpListener是用于创建和处理TCP连接的类。TcpClient用于创建TCP客户端,而TcpListener用于创建TCP服务器。 TcpClient类用于在客户端与服务器之间建立连接。可以通过TcpClient对象的构造函数创建实例,并使用Connect方法连接到指定的服务器和端口。一旦连接建立,就可以使用NetworkStream来发送和接收数据。 以下是一个简单的示例代码,演示了如何使用TcpClient发送数据: ```csharp using System; using System.Net.Sockets; class Program { static void Main() { try { TcpClient client = new TcpClient("127.0.0.1", 8080); NetworkStream stream = client.GetStream(); string message = "Hello, Server!"; byte[] data = System.Text.Encoding.ASCII.GetBytes(message); stream.Write(data, 0, data.Length); Console.WriteLine("Message sent to the server."); stream.Close(); client.Close(); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } } } ``` TcpListener类用于创建TCP服务器,它监听指定的端口,并等待客户端的连接请求。可以使用AcceptTcpClient方法来接受客户端连接,并返回一个TcpClient对象以进行数据传输。 以下是一个简单的示例代码,演示了如何使用TcpListener接收数据: ```csharp using System; using System.Net; using System.Net.Sockets; class Program { static void Main() { TcpListener server = null; try { // 设置监听IP和端口 IPAddress ipAddress = IPAddress.Parse("127.0.0.1"); int port = 8080; server = new TcpListener(ipAddress, port); // 开始监听 server.Start(); Console.WriteLine("Server started. Waiting for clients..."); // 接受客户端连接 TcpClient client = server.AcceptTcpClient(); // 获取客户端的网络流 NetworkStream stream = client.GetStream(); byte[] data = new byte[1024]; // 读取客户端发送的数据 int bytesRead = stream.Read(data, 0, data.Length); string message = System.Text.Encoding.ASCII.GetString(data,0, bytesRead); Console.WriteLine("Received message: " + message); stream.Close(); client.Close(); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } finally { if (server != null) server.Stop(); } } } ``` 这些是TcpClientTcpListener的基本用法示例。你可以根据你的需求进行进一步的开发和处理。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值