简体   繁体   English

Java:ObjectInputStream +套接字

[英]Java: ObjectInputStream + Socket

I'm creating simple peer to peer game. 我正在创建简单的点对点游戏。 Currently I'm working on Server/Client(Node) side. 目前,我正在服务器/客户端(节点)方面。 I occured strange problem, I can create ObjectOutputStream from socket, but program stops at creation of ObjectInputStream . 我发生了一个奇怪的问题,我可以从套接字创建ObjectOutputStream ,但是程序在创建ObjectInputStream 停止 To store sockets and create streams I'm using my own class(code below). 为了存储套接字并创建流,我使用了自己的类(下面的代码)。 What I'm doing wrong ? 我做错了什么?

public void run() {
    try {
        while (this.listen) {

            temp = serverSocket.accept();
            sockList.addSocket(temp);
            sockList.addObjOutStrm(temp);
            sockList.addObjInStrm(temp); // <------------------------ program stops


            setChanged();
            notifyObservers(temp);

            System.out.println("SERVER: Dodalem uzytkownika, oto pelna lista:\n\n"
                            + sockList + "\n");

            synchronized (sockList) {
                for (ObjectOutputStream oos : sockList.getOOSList()) {
                    oos.writeObject(sockList.extractToString());
                }
            }
        }
    } catch (IOException e) {
        System.err.println("SERVER: Błąd I/O serwera podczas nasluchu");
        //e.printStackTrace();
    }
}

My Own class to store sockets and streams: 我自己的用于存储套接字和流的类:

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class SocketList {
    private List<ObjectOutputStream> obOutStrList;
    private List<ObjectInputStream> obInStrList;
    private List<Socket> sockList;

    private int maxUsers;
    private int currentUsers;

    public SocketList() {
        obOutStrList = Collections
                .synchronizedList(new ArrayList<ObjectOutputStream>());
        obInStrList = Collections
                .synchronizedList(new ArrayList<ObjectInputStream>());
        sockList = Collections.synchronizedList(new ArrayList<Socket>());

        maxUsers = 4;
        currentUsers = 0;
    }

    synchronized public void addSocket(Socket sock) {
        if (sockList.size() < 4) {
            sockList.add(sock);
            currentUsers++;
        } else {
            System.out.println("sockList: Blad max uzytkownikow");
        }
    }

    synchronized public void addObjOutStrm(Socket sock) {
        try {
            obOutStrList.add(new ObjectOutputStream(sock.getOutputStream()));
        } catch (IOException e) {
            System.out.println("Problem z uzyskaniem strumienia wyjsciowego dla " + sock.getInetAddress().getHostAddress().toString());
            e.printStackTrace();
        }
    }

    synchronized public void addObjInStrm(Socket sock) {
        try {
            obInStrList.add(new ObjectInputStream(sock.getInputStream()));
        } catch (IOException e) {
            System.out.println("Problem z uzyskaniem strumienia wejsciowego dla " + sock.getInetAddress().getHostAddress().toString());
            e.printStackTrace();
        }
    }

    synchronized public void removeSock(Socket s) {
        if (sockList.contains(s)) {
            System.out.println("SOCKETLIST: Usuwam " + s.toString());
            sockList.remove((Socket) s);
        }
    }

    synchronized public List<Socket> getSockList() {
        return sockList;
    }

    synchronized public List<ObjectOutputStream> getOOSList() {
        return obOutStrList;
    }

    synchronized public List<ObjectInputStream> getOISList() {
        return obInStrList;
    }

    public String toString() {
        return sockList.toString();
    }

    public String[] extractToString() {
        String[] retArr = new String[currentUsers];

        for (int i = 0; i < sockList.size(); i++)
            retArr[i] = sockList.get(i).getInetAddress().getHostAddress()
                    .toString();

        return retArr;
    }

}

Are you sure, you want to do this? 你确定你要这么做吗? Reading an writing objects is not very portable, use some kind of protocol with a data structure like XML or JSON for communication. 读取书写对象不是很方便,请使用带有XML或JSON等数据结构的某种协议进行通讯。 This is far more portable. 这是更可移植的。
To your problem: 给你的问题:

new ObjectInputStream(sock.getInputStream())

will block and wait until the header has been written to the stream, as the JavaDoc states: 将阻塞并等待,直到将标头写入流为止,如JavaDoc所述:

This constructor will block until the corresponding ObjectOutputStream has written and flushed the header. 该构造函数将阻塞,直到相应的ObjectOutputStream写入并刷新了头为止。

Overall, I strongly suggest you a different architecture, use multi-threading to handle the client connections on the server, possibly using a thread pool and maybe even message queues. 总体而言,我强烈建议您使用其他体系结构,使用多线程处理服务器上的客户端连接,可能使用线程池,甚至可能使用消息队列。 See package java.util.concurrent for all you need for this. 请参阅软件包java.util.concurrent了解所需的全部内容。

Have a look here, for a start: http://tutorials.jenkov.com/java-multithreaded-servers/multithreaded-server.html 从这里开始看看: http : //tutorials.jenkov.com/java-multithreaded-servers/multithreaded-server.html

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

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