How I can to create python(or swift) TCP client for my TCP c# server?
c# API for my TCP server:
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;
}
I try it(python) :
import socket
sock = socket.socket()
sock.connect(('localhost', 4021))
But I don't uderstand how I must to send my login and password (like in API for c#).
I don`t undestand what you want to implement. If you want to run Python code in C#, then look at this IronPython
If you want to implement TCP client in C#, then try smth like this:
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);
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.