java服务器/客户端字符串延迟

edqdpe6u  于 2021-07-09  发布在  Java
关注(0)|答案(3)|浏览(358)

我正在创建一个局域网游戏,它接受字符串并从结构化英语中解析它们,并将它们显示在网格上。我已经创建了服务器和客户端,它的工作,但我有一些问题。当我发送一个字符串时,它不会立即出现在另一台机器上。由于某些原因,字符串只在另一台机器发送某些内容时才会发送到另一台机器。我不知道为什么会这样。你能帮我找出为什么不能马上寄出去吗。谢谢
服务器代码:

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

客户代码:

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) {}
        }
}
}

代码工作,但我不知道为什么有一个条件,为其他机器发送的东西。
谢谢你的时间。

rur96b6h

rur96b6h1#

你试过了吗 printWriter.flush() 每次写入/打印后?

rmbxnbpk

rmbxnbpk2#

你的代码中有很多编译问题。某些类和对象丢失,无法解析。
但我还是试着找出问题所在。
原因可能是:
发送新行字符 \nprintWriter.println(commandMessage+"\n"); 声明,删除 \n .
客户机和服务器都是先写的 printWriter.println(commandMessage+"\n"); 陈述,让它在任何一堂课上都是最后的
代码如下:
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");
    }
}
dgsult0t

dgsult0t3#

正如布拉吉指出的,这里有很多小问题。在服务器端,主要的顺序如下:

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

这意味着 printWriter 在服务器侦听、阻止等待并接受来自客户端的连接之前,它甚至不存在。
如果您想打开连接进行读写,而不想从客户端发送任何信息,请从客户端发送握手。您可以复制smtp,并使用 HELO <myname> . 甚至告诉服务器是谁在打电话。
进一步阅读后更新:
我一直都像你一样,使用隐式连接,当你使用 getOutputStream() 在客户端。然而, Socket 允许您使用socket#connect()手动连接现有的套接字。试试看,对你来说,也许比握手更有效。

相关问题