简体   繁体   中英

TCP communication issues between Delphi and c#

I am trying to send text lines from ac# client to a delphi server using TCP.Both are just to be run on the localhost. I want the client to send lines of text whenever it suits and the server to be able to read in and process them from the incoming stream one line at a time whenever it suits.

The code below achieves this once with the delphi memo displaying 'some line of text 1'. After that the c# returns and exception saying that the connection was forcibly closed.

I can achieve the desired effect if I close the client connection and re-establish a new one each time a line of text is sent. But this is very slow and not feasible for my intended use.

I am new to TCP and have little idea what I am doing! Any help in achieving the desired result would be very much appreciated.

Delphi Server code is....

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# code is.............

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
    ////////////////////////////////////////////////


}



    }

After you create your instance of the TcpClient, you actually need to Connect .

You can also use IPAddress a = IPAddress.Loopback; for the loopback adapter so that you don't need to parse it.

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

    theclient.Connect(server,port);
}

I don't know the exact behaviour of the socket class in Delphi, but it looks for me like the server closes the connection if the OnAccept procedure TForm1.TcpServer1Accept ends. Therefor you should have there also a loop, maybe with an end critera:

procedure TForm1.TcpServer1Accept(Sender: TObject; ClientSocket: TCustomIpClient);
var
  somestring : string;
begin
  do
    begin
      somestring := ClientSocket.Receiveln('#$D#$A');
      Memo1.Lines.Add(somestring);
    end;
  while(somestring.length > 0);
end; //TForm1.TcpServer1Accept ends

This will be no valid Delphi code, as I haven't used Delphi/Pascal for a long time, but I think you will get the idea...

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM