Java Server/Client string delay

半腔热情 提交于 2020-01-06 18:25:07

问题


i am creating a LAN game that accepts strings and parses them from structured english and displays them on a grid. i have created the server and client and it works but im having some issues. when i send a string it doesnt appear on the other machine right away. for some reason the string is only sent to the other machine once the other machine sends something over. i dont know why this happens. Could you please help me find out why it doesnt send straight away. Thanks

Server Code:

import java.awt.Point;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
public class studentServer{
static ServerSocket serverSocket;
static Socket socket;
static PrintWriter printWriter;
static BufferedReader bufferedReader;
static Thread thread;
Console console = new Console();


public ServerPlayergameMain gm;
    public static void main(String args[]) throws Exception{
}
public void run(String commandMessage){
    while(true){
        try{
            printWriter.println(commandMessage+"\n");
            String input = bufferedReader.readLine();//reads the input from textfield
            console.readLine("Client message: "+input);//Append to TextArea
        }catch(Exception e){}
    }
}
    public void serverStartActionPerformed() {
    System.out.println("Server has started!");
    try{
        serverSocket = new ServerSocket (8888); // socket for the server
        socket = serverSocket.accept(); // waiting for socket to accept client
        JOptionPane.showMessageDialog(null, "Your opponent has connected!", "Opponent Connection!", JOptionPane.INFORMATION_MESSAGE);
        gm = new ServerPlayergameMain();
        gm.setVisible(true);
        bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream())); // reads line from input streamer
        printWriter = new PrintWriter(socket.getOutputStream(),true);
    }catch(IOException | HeadlessException e){
        System.out.println("Server not running!"); //print message if server is not running
    }
}
}

Client Code:

import java.io.*;
import java.net.*;
import javax.swing.JOptionPane;
public class StudentClient {
static Socket socket;
static PrintWriter printWriter;
static BufferedReader bufferedReader;
static Thread thread;
Console console = new Console();


public ClientPlayergameMain gm;

public void Clients(String address) {
    try{
        socket=new Socket("localhost",8888);//Socket for client
        //below line reads input from InputStreamReader
        bufferedReader=new BufferedReader(new InputStreamReader(socket.getInputStream()));
        //below line writes output to OutPutStream
        printWriter=new PrintWriter(socket.getOutputStream(),true);
        JOptionPane.showMessageDialog(null, "Connected to server successfully", "Success", JOptionPane.INFORMATION_MESSAGE);
        gm = new ClientPlayergameMain();
        gm.setVisible(true);
        System.out.println("Connected");//debug code
    }catch(Exception e){
       JOptionPane.showMessageDialog(null, "No Connection to server", "Error", JOptionPane.ERROR_MESSAGE);
        System.out.println("Not Connected");
    }    
}
public static void run(String commandMessage){
        while(true){
            try{
                printWriter.println(commandMessage+"\n");
                String input = bufferedReader.readLine();
                System.out.println("From server:" +input);
            }catch(Exception e) {}
        }
}
}

The code works but i dont know why there is a condition for the other machine to send something.

Thanks for your time.


回答1:


A lot of compilation problems are there in you code. Some of the classes and objects are missing to resolve.

Still I have tried it to figure out the issue.

It may be the reasons:

  • sending new line character \n in printWriter.println(commandMessage+"\n"); statement, just remove \n.
  • client and server both are writing first in printWriter.println(commandMessage+"\n"); statement, make it last in anyone class

Here is the code:

StudentServer.java:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class StudentServer {
    static ServerSocket serverSocket;
    static Socket socket;
    static PrintWriter printWriter;
    static BufferedReader bufferedReader;
    static Thread thread;

    public static void main(String args[]) throws Exception {
        StudentServer studentServer = new StudentServer();
        studentServer.serverStartActionPerformed();
        studentServer.run("server");
    }

    public void run(String commandMessage) {
        if (true) {
            try {
                printWriter.println(commandMessage);
                String input = bufferedReader.readLine();// reads the input from textfield
                System.out.println("Client message: " + input);// Append to TextArea
            } catch (Exception e) {
            }
        }
    }

    public void serverStartActionPerformed() {
        System.out.println("Server has started!");
        try {
            serverSocket = new ServerSocket(8888); // socket for the server
            socket = serverSocket.accept(); // waiting for socket to accept client
            bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream())); // reads
                                                                                                 // line
                                                                                                 // from
                                                                                                 // input
                                                                                                 // streamer
            printWriter = new PrintWriter(socket.getOutputStream(), true);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("Server not running!"); // print message if server is not running
        }
    }
}

StudentClient.java:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class StudentClient {
    static Socket socket;
    static PrintWriter printWriter;
    static BufferedReader bufferedReader;
    static Thread thread;

    public void clients() {
        try {
            socket = new Socket("localhost", 8888);// Socket for client
            // below line reads input from InputStreamReader
            bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            // below line writes output to OutPutStream
            printWriter = new PrintWriter(socket.getOutputStream(), true);
            System.out.println("Connected");// debug code
        } catch (Exception e) {
            System.out.println("Not Connected");
        }
    }

    public void run(String commandMessage) {
        if (true) {
            try {
                String input = bufferedReader.readLine();
                System.out.println("From server:" + input);
                printWriter.println(commandMessage);
            } catch (Exception e) {
            }
        }
    }

    public static void main(String args[]) throws Exception {
        StudentClient studentClient = new StudentClient();
        studentClient.clients();
        studentClient.run("client");
    }
}



回答2:


Have you tried printWriter.flush() after each write/print?




回答3:


There are quite a few little problems, as Braj points out. The main one is in this sequence on your server side:

   serverSocket = new ServerSocket (8888); // socket for the server
   socket = serverSocket.accept(); // BLOCKS waiting for socket to accept client
   // ..
   printWriter = new PrintWriter(socket.getOutputStream(),true);

This means that printWriter, which you use to write to the client, doesn't even exist until after the server has listened for, blocked waiting on, and accepted a connection from the client.

If you want the connection to be opened for reading and writing without seeming to send anything from the client, send a handshake from the client. You could copy SMTP, and use HELO <myname>. That even tells the server who's calling.

Update after further reading:

I've always done like you have, and used the implicit connect that happens when you use getOutputStream() on the client side. However, Socket does allow you to connect an existing socket manually, using Socket#connect(). Try that, maybe it will work better than a handshake, for you.



来源:https://stackoverflow.com/questions/22330065/java-server-client-string-delay

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!