gpt4 book ai didi

c# - Delphi和c#之间的TCP通信问题

转载 作者:可可西里 更新时间:2023-11-01 02:33:48 26 4
gpt4 key购买 nike

我正在尝试使用 TCP 从 c# 客户端向 delphi 服务器发送文本行。两者都只是在本地主机上运行。我希望客户端在合适的时候发送文本行,并且服务器能够在合适的时候一次一行地从传入流中读入和处理它们。

下面的代码通过显示“某行文本 1”的 delphi 备忘录实现了这一点。之后,c# 返回并显示连接被强行关闭的异常。

如果每次发送一行文本时关闭客户端连接并重新建立一个新连接,我就可以达到预期的效果。但这非常慢,并且不适合我的预期用途。

我是 TCP 的新手,对自己在做什么一无所知!非常感谢任何有助于实现预期结果的帮助。

Delphi 服务器代码是....

procedure TForm1.FormCreate(Sender: TObject);
begin

Memo1.Lines.Clear;

//Server initialization
TcpServer1 := TTcpServer.Create(Self);
TcpServer1.OnAccept := TcpServer1Accept;
TcpServer1.LocalPort := IntToStr(DEFAULT_PORT);
TcpServer1.Active := true;


end; //TForm1.FormCreate procedure ends


procedure TForm1.TcpServer1Accept(Sender: TObject;
ClientSocket: TCustomIpClient);
var
somestring : string;
begin

somestring := ClientSocket.Receiveln('#$D#$A');
Memo1.Lines.Add(somestring);

end; //TForm1.TcpServer1Accept ends

c#代码是......

public static void Main (string[] args)
{

bool connectionEstablished = false;
int messageNum = 1;
TcpClient theclient = new TcpClient();

//first try establish a successful connection before proceeding
Console.WriteLine("Waiting for server......");
while (connectionEstablished == false) {

connectionEstablished = true;

try {

Int32 port = 2501;
string server = "127.0.0.1"; //the ip of localhost

theclient = new TcpClient(server, port);

} catch {

Console.WriteLine("Could not find AI server");
connectionEstablished = false;
}


} //while (connectionEstablished == false) ends

Console.WriteLine("Connected to server");

////////////////////////////////////////
while (true) {

try
{

string message = "some line of text " + messageNum.ToString() + "#$D#$A";

// Translate the passed message into ASCII and store it as a Byte array.
Byte[] data = System.Text.Encoding.ASCII.GetBytes(message);

NetworkStream stream = theclient.GetStream();

stream.Write(data, 0, data.Length); //working

messageNum = messageNum + 1;

}
catch (ArgumentNullException e)
{
Console.WriteLine("ArgumentNullException: {0}", e);
Console.WriteLine("\n Press Enter to continue...");
Console.Read();

}
catch (SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
Console.WriteLine("\n Press Enter to continue...");
Console.Read();

}


System.Threading.Thread.Sleep(2500);

} //while (true) ends
////////////////////////////////////////////////


}



}

最佳答案

创建 TcpClient 实例后,您实际上需要Connect

你也可以使用 IPAddress a = IPAddress.Loopback;对于环回适配器,这样您就不需要解析它。

try 
{
Int32 port = 2501;
string server = "127.0.0.1"; //the ip of localhost
theclient = new TcpClient();

theclient.Connect(server,port);
}

关于c# - Delphi和c#之间的TCP通信问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18693082/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com