Incomplete messages (C# TCP/IP Client)

前端 未结 3 1989
独厮守ぢ
独厮守ぢ 2020-12-20 00:05

First of all, I\'m absolutely not a network programmer. What I try to do, is a very simple TCP/IP communication between a Java server and a C# client.

Java server:

3条回答
  •  隐瞒了意图╮
    2020-12-20 00:28

    Take a look at this example...

    Java TCP Server...

    import java.net.*;
    import java.io.*;
    
    public class TcpServer
    {
        public static void main(String h[])
        {
            try
            {
                ServerSocket serverSocket = new ServerSocket(1100);
                Socket socket = serverSocket.accept();
                System.out.println("Client Accepted");
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                System.out.println("Received: " + bufferedReader.readLine());
                PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()), true);
                printWriter.println("Hello Theo. Welcome to socket programming.");
            } catch (Exception e)
            {
                System.out.println(e);
            }
        }
    }
    

    C# TCP Client...

    using System;
    using System.IO;
    using System.Net.Sockets;
    
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                var client = new TcpClient("localhost", 1100);
                var stream = client.GetStream();
                var streamWriter = new StreamWriter(stream);
                streamWriter.WriteLine("My name is Theo");
                streamWriter.Flush();
                var streamReader = new StreamReader(stream);
                Console.WriteLine("Received: " + streamReader.ReadLine());
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
    
            Console.WriteLine("Press a key to continue.");
            Console.ReadKey();
        }
    }
    

提交回复
热议问题