我正在尝试在一台服务器和一台客户端之间创建一个简单的传输。我正在尝试将对象从客户端发送到服务器。我已经检查了我的代码很多次了,我真的不知道为什么 t 不起作用。另外,我想补充一点,我在 netbeans 中创建了两个独立的项目,一个用于客户端,一个用于服务器。代码如下:
客户:
package client;
import java.net.*;
import java.io.*;
import java.util.Scanner;
import java.io.Serializable;
class Object implements Serializable {
String one;
String two;
public Object(String one, String two){
this.one = one;
this.two = two;
}
@Override
public String toString(){
return "\nOne: " + one +"\nTwo: " + two;
}
}
public class Client {
public static void main(String[] args){
try {
Object obj= new Object ("Something", "Else");
Socket sock = new Socket("127.0.0.1", 1111);
ObjectOutputStream oos = new ObjectOutputStream(sock.getOutputStream());
System.out.println("Connecting to "+ sock.getInetAddress()+ " and port "+sock.getPort());
System.out.println("Local Address :"+sock.getLocalAddress()+" Port:"+sock.getLocalPort());
oos.writeObject(obj);
oos.flush();
oos.close();
sock.close();
System.out.println("Connection Closing...");
} catch (Exception ex){
System.out.println("No Conenction");
}
}
}
服务器:
<!-- language: lang-java -->
package server;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.*;
import java.io.*;
class Object implements Serializable {
String one;
String two;
public Object(String one, String two){
this.one = one;
this.two = two;
}
@Override
public String toString(){
return "\nOne: " + one +"\nTwo: " + two;
}
}
public class Server {
public static void main(String[] args){
try{
ServerSocket server = new ServerSocket(1111,10);
System.out.println("Waiting Incoming Connection...");
System.out.println("Local Address :"+server.getInetAddress()+" Port:"+server.getLocalPort());
Socket sock = server.accept();
ObjectInputStream ois = new ObjectInputStream(sock.getInputStream());
Object ob=new Object ("Once", "Upon"); //for test
Object obj2= null;
try{
obj2 = (Object )ois.readObject();
System.out.println(obj2);
}catch (Exception ex){
System.out.println("nothing...");
}
System.out.println(ob);
ois.close();
}catch (Exception ex){
System.out.println("Error during I/O");
ex.getMessage();
ex.printStackTrace();
}
}
}
代码有效,但从未发送对象 =/ 。我收到异常消息“什么都没有。”。该连接有效,因为它们使用简单的消息 BufferedReader() 、 BufferedWritter() 交换消息。问题在于对象....