我有一个多人Java游戏(四个客户端和一个服务器),所有类都在一个文件中我决定重写主类并将代码保存在多个较短的类中。一切似乎都没问题(没有语法错误)或运行时错误),从服务器端看起来很好,但不是从客户端 我决定使用Print语句来获取bug,似乎客户端无法处理下面的代码:
public class ServerManager implements Runnable {
public static BufferedReader in;
public static PrintWriter out;
private Socket socket;
@Override
public void run() {
try
{
socket = Connection.connectToServer(GameStatus.serverIP, GameStatus.serverPort);
if(socket != null) {
return;
} else {
}
in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);
此特定区域的应用程序的工作版本如下所示
BufferedReader in;
PrintWriter out;
public static void main(String[] args) {
....
....
....
private class startClient implements Runnable {
private Socket socket;
@Override
public void run() {
try
{
try {
socket = new Socket(serverIP, serverPort);
} catch (Exception ex) {
return;
}
in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);
我的代码有任何问题吗?
答案 0 :(得分:0)
好吧,我把try放在套接字连接的开头,并在类的末尾捕获异常,只是尝试一下并在套接字连接后保持捕获并且它工作正常。
try
{
try{
socket = Connection.connectToServer(GameStatus.serverIP, GameStatus.serverPort);
//if(socket != null) {
//return;
//} else {
// }
} catch (Exception ex){
JOptionPane.showMessageDialog(null, "Can not connect to server!");
if(ex.toString().trim().equals("java.net.SocketException: Connection reset"))
{
JOptionPane.showMessageDialog(null, "Server is down!\nThe game will now exit...");
System.exit(0);
}
//else
}
//}
in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);