客户端-服务器套接字

时间:2018-10-10 10:37:51

标签: java sockets serversocket

我试图在Java中实现客户端服务器,在该客户端中读取客户端的输入并在服务器中执行UperCase,然后返回到客户端并打印UperCase。 我使用ObjectOutputStream和ObjectInputStream进行读写,但是当我在客户端中键入msg时,程序向我显示此错误:

  

Digite uma味精   卡萨   java.io.EOFException       在java.io.DataInputStream.readUnsignedShort(未知源)       在java.io.ObjectInputStream $ BlockDataInputStream.readUnsignedShort(未知源)       在java.io.ObjectInputStream $ BlockDataInputStream.readUTF(未知源)       在java.io.ObjectInputStream.readUTF(未知来源)       在Client.java.Client.main(Client.java:32)

我的客户端是这个:

  Object.keys(o).forEach(function (k) {
      if (o[k] !== null && typeof o[k] === 'object') {
          if(parent) {
            console.log(parent);
            if(!o.children) {
              o.children = [];
            }
            o.children.push({id: k + ": " + o[k].value})
          } else {
            o.id = k + ": " + o[k].value
          }

          _this.iter(o[k], k);
          return;
      }
  });

这是我的服务器端:

package Client.java;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

public class Client {

    public static void main(String[] args) {

        //estabelece conexao 
        // trocar msg com o server

        try {
            //cria conexao entre  client e servidor
            Socket socket = new Socket("localhost",5558);

            //cria input and output
            ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());
            ObjectInputStream input = new ObjectInputStream(socket.getInputStream());

            Scanner scan = new Scanner(System.in);
            System.out.println("Digite uma msg");
            String word = scan.nextLine();
            output.writeUTF(word);
            output.flush();
            word = input.readUTF();
            System.out.println("Upercase"+ word);

            input.close();
            output.close();
            socket.close();

        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

是因为我的服务器正在关闭流吗? 以及如何解决它并仍然关闭流? 谢谢您的帮助。

1 个答案:

答案 0 :(得分:1)

您应该在Servidor中使用

output.writeUTF(msg.toUpperCase());

而不是

output.writeObject(msg.toUpperCase());