java.io.StreamCorruptedException:无效的流标题:72657175

时间:2011-12-16 12:26:14

标签: java sockets

嘿我正在实施基于客户端服务器聊天的电子投票系统。 当我运行服务器时,它运行没有任何问题,但没有打印以及客户端。但是一旦我将输入提供给客户端,它就会给我以下异常和崩溃。这是服务器和客户端的代码。那么你认为我应该怎么做才能启动发动机呢?

    package engine;
import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.GregorianCalendar;

public class Server {
ServerSocket server;
int port = 6000;

public Server() {
    try {
        server = new ServerSocket(6000);
    } catch (IOException e) {
        e.printStackTrace();
    }
}


public void handleConnection(){
    try {
        while(true){
            Socket connectionSocket;
            connectionSocket = server.accept();
            new ConnectionHandler(connectionSocket);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

public static void main(String[] args) {
    Server server = new Server();
    server.handleConnection();
}
}    
class ConnectionHandler implements Runnable {
Socket connectionSocket;
Calendar votingStartTime;
Calendar votingEndTime;
boolean timeUp;
ObjectInputStream inFromClient;
ObjectOutputStream outToClient;
BufferedWriter outToFile;
BufferedReader inFromAdmin;
ArrayList<SingleClient> clients = new ArrayList<SingleClient>();
ArrayList<Candidate> candidates;

这是Exception来自的代码的一部分:

    public ConnectionHandler(Socket socket) {
    try {
        this.connectionSocket = socket;
        votingStartTime = new GregorianCalendar();
        outToClient = new ObjectOutputStream(
                connectionSocket.getOutputStream());
        inFromClient = new ObjectInputStream(
                connectionSocket.getInputStream());
        inFromAdmin = new BufferedReader(new InputStreamReader(System.in));
        startVotingSession();
        Thread t = new Thread(this);
        t.start();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

这是我提供输入时客户端的主要方法Exception:

public static void main(String[] args) throws Exception {
    client c = new client();
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    String input;
    while(true){
        input = br.readLine();
        if(input.equals("0")){
            c.register();
        }else if(input.equals("1")){
            c.login();
        }else if(input.equals("2")){
            c.listCandidates();
        }else if(input.equals("3")){
            c.vote();
        }else if(input.equals("4")){
            c.checkResults();
        }else if(input.equals("5")){
            c.checkFinalResults();
        }else if(input.equals("6")){
            c.logout();
        }else {
            break;
        }
    }
}
}

1 个答案:

答案 0 :(得分:0)

没有看到相关的代码,我猜你会在现有的套接字InputStream上重新创建ObjectInputStream。您必须为每个套接字创建一次对象流并重新使用它们,直到您完全使用套接字连接。此外,您应该始终在创建后立即刷新ObjectOutputStream以避免死锁。