Java,Socket,发送消息

时间:2014-06-22 05:23:27

标签: java sockets client-server chat

我正在尝试制作多人游戏,但首先我要尝试使用简单的扫描仪和打印代码

我有两个文件," cl.java "是客户," server.java "是服务器。

我想做什么?

客户端向其他客户发送消息,要求进行游戏 这个初始消息不会在我的代码中运行,我想我无法在课程clientThread.sendText(un + " iWantToPlay");之外使用ConnectThread

你认为什么?

此代码发生错误:

        public void sendText(String text) {
        try {
            oos.writeObject(text);

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

使用oos.writeObject(text);

这是 Server.java

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;

public class Server {

ServerSocket serverSocket;
ArrayList<ServerThread> allClients = new ArrayList<ServerThread>();

public static void main(String[] args) {
    new Server();

}

public Server() {
    // ServerSocket is only opened once !!!

    try {
        serverSocket = new ServerSocket(6000);

        System.out.println("Waiting on port 6000...");
        boolean connected = true;

        // this method will block until a client will call me
        while (connected) {
            Socket singleClient = serverSocket.accept();
            // add to the list
            ServerThread myThread = new ServerThread(singleClient);
            allClients.add(myThread);
            myThread.start();
        }

        // here we also close the main server socket
        serverSocket.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

class ServerThread extends Thread {
    Socket threadSocket;
    String msg;
    boolean isClientConnected;
    InputStream input;
    ObjectInputStream ois;
    OutputStream output;
    ObjectOutputStream oos; // ObjectOutputStream

    public ServerThread(Socket s) {
        threadSocket = s;
    }

    public void sendText(String text) {
        try {
            oos.writeObject(text);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public void run() {

        try {
            input = threadSocket.getInputStream();
            ois = new ObjectInputStream(input);
            output = threadSocket.getOutputStream();
            oos = new ObjectOutputStream(output);

            // get the user name from the client and store
            // it inside thread class for later use
            // msg = (String) ois.readObject();
            msg = (String) ois.readObject();

            for (ServerThread t : allClients)
                t.sendText(msg);

            isClientConnected = true;
            System.out.println("connect ... ");

            // System.out.println(msg);
            // for(ServerThread t:allClients)
            // t.sendText("User has connected...");

            // send this information to all users
            // dos.writeUTF(userName + " has connected..");
            // for(ServerThread t:allClients)
            // t.sendText(msg);

            while (isClientConnected) {

                try {
                    msg = (String) ois.readObject();
                    System.out.println(msg);

                    for (ServerThread t : allClients)
                        t.sendText(msg);
                } catch (Exception e) {

                }
            }
            // close all resources (streams and sockets)
            ois.close();
            oos.close();
            threadSocket.close();

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

}

这是 cl.java

import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

public class cl {
public static final String HOST = "127.0.0.1";
public static final int PORT = 6000;

static ConnectThread clientThread;
boolean isConnected;

static boolean isOnline = false;
static Scanner scanner = new Scanner(System.in);
static String msg;
static String un;
static String op = "none";
static int turn = 1;

public static void main(String[] args) {
    boolean running = true;

    System.out.print("Enter a username: ");
    un = scanner.nextLine();

    System.out.print("invite or wait ?");
    msg = scanner.nextLine();

    if (msg.equalsIgnoreCase("invite")) {
        System.out.print("Enter an opponent: ");
        op = scanner.nextLine();
    }

    new cl();

    if (op.equalsIgnoreCase("amjad")) {
        clientThread.sendText(un + " iWantToPlay");
    }


}

public String getWord(String line,int i) {
    String arr[] = line.split(" ", 2);
 return arr[i];

}

public cl() {
    connectUser();
}

public void connectUser() {
    clientThread = new ConnectThread();
    clientThread.start();

}

class ConnectThread extends Thread {
    InputStream input;
    OutputStream output;
    ObjectOutputStream oos;
    Socket s;

    public void sendText(String text) {
        try {
            oos.writeObject(text);

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public void run() {
        try {
            s = new Socket(HOST, PORT);
            output = s.getOutputStream();
            oos = new ObjectOutputStream(output);

            isOnline = true;
            isConnected = true;

            new ListenThread(s).start();

/*              while (isOnline) {
                    msg = scanner.nextLine();
                    clientThread.sendText(un + ": " + msg);
                }
*/
        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

class ListenThread extends Thread {

    Socket s;
    InputStream input;
    ObjectInputStream ois;

    public ListenThread(Socket s) {
        this.s = s;
        try {
            input = s.getInputStream();
            ois = new ObjectInputStream(input);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    public void run() {
        while (isConnected) {
            try {
                final String inputMessage = (String) ois.readObject();
                String user;
                user = getWord(inputMessage,1);
                String message = getWord(inputMessage,2);

                /*if (!user.equals(un)) {
                    System.out.println(inputMessage);
                }*/

                if (message.equalsIgnoreCase("iwanttoplay")) {
                    System.out.println(user + " wants to play, accept? y\n");
                    msg = scanner.nextLine();
                    clientThread.sendText(un + " " + msg);
                }
                else if (message.equalsIgnoreCase("yesiwanttoplay")) {
                    System.out.println(un + " accepted invitation, "  + un + " against " + user);
                    turn = 1;
                    play(un,user);
                }
                else if (message.equalsIgnoreCase("noidontwanttoplay")) {
                    System.out.println(user + " denied invitation.. ");
                }
                else if (message.equalsIgnoreCase("x") || message.equalsIgnoreCase("o")) {
                    System.out.println(user + " played .. " + message);
                    turn = 1;
                    play(un,user);
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    }
}

public void play(String me, String him) {
    if (turn == 1) {
        System.out.println("your turn,... play a move..x or o ..");
        msg = scanner.nextLine();
        clientThread.sendText(un + " " + msg);
        turn = 2;
    }
}

}

这是我的错误

Exception in thread "main" java.lang.NullPointerException
at cl$ConnectThread.sendText(cl.java:68)
at cl.main(cl.java:38)

1 个答案:

答案 0 :(得分:0)

  

线程中的xception&#34; main&#34;显示java.lang.NullPointerException   在cl $ ConnectThread.sendText(cl.java:68)

你应该能够自己解决这个问题。有问题的行似乎是

oos.writeObject(text);

所以显然oos在那时为空。

您不需要StackOverflow来整理NullPointerExceptions.