简体   繁体   English

Java中的客户端套接字编程-从服务器端写入客户端套接字的麻烦

[英]Client-socket programming in Java - trouble with writing to the client socket from server side

So I am trying to create a simple server client program, where multiple clients can connect to a single server. 因此,我试图创建一个简单的服务器客户端程序,其中多个客户端可以连接到单个服务器。 I'm running a thread on both client side and server side. 我在客户端和服务器端都运行一个线程。 I have a file "loginuser.txt" which has text for 5 lines. 我有一个文件“ loginuser.txt”,其中有5行文字。 This code is the server thread. 此代码是服务器线程。 When I call a outToClient.println("xxx") or anything, the Client is NOT receiving MORE than ONE line at a time. 当我调用outToClient.println(“ xxx”)或其他任何内容时,客户端一次不会收到多于一个的行。 Each time the user enters anything on the keyboard (on client terminal), the next line of the file is being displayed on the same terminal. 每次用户在键盘上(客户端)上输入任何内容时,文件的下一行都会显示在同一终端上。 Can someone tell me why this is happening? 有人可以告诉我为什么会这样吗? Where am I going wrong? 我要去哪里错了? Basic issue: For a println() of a single line from server to client, it seems like I have to type something every time on the client side. 基本问题:对于从服务器到客户端的一行的println(),似乎我每次都必须在客户端上键入一些内容。

BufferedReader inFromUser=new BufferedReader(new InputStreamReader(System.in));
BufferedReader inFromClient=new BufferedReader(new InputStreamReader(client.getInputStream()));
BufferedReader userlogr=new BufferedReader(new FileReader("loginuser.txt"));
PrintWriter outToClient = new PrintWriter(client.getOutputStream(), true);
if(check==1)
    {
        fromclient=inFromClient.readLine();
        if(fromclient.compareTo("xxx")==0)
        {
            String line;
            while((line=userlogr.readLine())!=null)
            {
                System.out.println(line);
                outToClient.println(line);
                outToClient.flush();
            }

        }
    }

I have had this issue before. 我以前有过这个问题。 There are usually three things 通常有三件事

1.)Also check the strings your sending has "\\n" at the end. 1.)还要检查您发送的字符串末尾有“ \\ n” using \\n and println would mess up the carriage return since it would be doubled.Remove any extra "\\n" and try it.(High possibility this is the problem in your case) 使用\\ n和println会使回车符混乱,因为它将被加倍。删除任何多余的“ \\ n”并尝试。(很可能是您所遇到的问题)

2.) The client side does not have a while loop to output the entire data being passed. 2.)客户端没有while循环来输出正在传递的整个数据。 You are sending the data line by line. 您正在逐行发送数据。 Check if the client is closing itself after the data is received. 接收数据后,检查客户端是否正在关闭自身。

3.) Check your threads on the client side. 3.)在客户端检查线程 I do not know how your client side thread works, but mine used to get blocked by other threads. 我不知道您的客户端线程是如何工作的,但是我的客户端线程曾经被其他线程阻塞。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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