如何为我的TCP c服务器创建python(或swift)TCP客户端?

2024-10-04 07:25:28 发布

您现在位置:Python中文网/ 问答频道 /正文

如何为我的TCP c服务器创建python(或swift)TCP客户端?你知道吗

我的TCP服务器的c#API:

Client client = Client();
bool Connect()
{
    UserInfo userInfo = new UserInfo("login", "pass");
    NetworkConnectionParam connectionParams = new NetworkConnectionParam("127.0.0.1", 4021);
    try
    {
        client.Connect(connectionParams,userInfo,ClientInitFlags.Empty);
    }
    catch
    {
        return false;
    }
    return client.IsStarted;
}

我试过了(python):

import socket

sock = socket.socket()
sock.connect(('localhost', 4021))

但我不明白我必须如何发送我的登录名和密码(就像c#的API一样)。你知道吗


Tags: 服务器clientapinewreturnconnectsockettcp
1条回答
网友
1楼 · 发布于 2024-10-04 07:25:28

我不明白你想实施什么。 如果您想在C#中运行Python代码,那么请看这个IronPython

如果要在C#中实现TCP客户机,请尝试以下方法:

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

 class Program
{
    static int port = 8005; // your port
    static void Main(string[] args)
    {
        // get address to run socket
        var ipPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), port);

        // create socket
        var listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        try
        {
            // binding
            listenSocket.Bind(ipPoint);

            // start listen
            listenSocket.Listen(10);

            Console.WriteLine("Server is working");

            while (true)
            {
                Socket handler = listenSocket.Accept();
                // recieve message
                StringBuilder builder = new StringBuilder();
                int bytes = 0; // quantity of received bytes 
                byte[] data = new byte[256]; // data buffer

                do
                {
                    bytes = handler.Receive(data);
                    builder.Append(Encoding.Unicode.GetString(data, 0, bytes));
                }
                while (handler.Available>0);

                Console.WriteLine(DateTime.Now.ToShortTimeString() + ": " + builder.ToString());

                // send response
                string message = "your message recieved";
                data = Encoding.Unicode.GetBytes(message);
                handler.Send(data);
                // close socket
                handler.Shutdown(SocketShutdown.Both);
                handler.Close();
            }
        }
        catch(Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
}

相关问题 更多 >