我正在尝试使用 TCP 将文本行从 ac# 客户端发送到 delphi 服务器。两者都只是在 localhost 上运行。我希望客户端在适合的时候发送文本行,并且服务器能够在适合的时候一次一行地从传入的流中读取和处理它们。
下面的代码通过显示“某行文本 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
////////////////////////////////////////////////
}
}