#java #sockets #exception
#java #сокеты #исключение
Вопрос:
У меня есть имя класса player
public JLabel imagen;
public String Nombre;
public Player(int x, int y, int width, int height, Icon icono, String name){
imagen = Player(x, y, width, height, icono);
Nombre = name;
}
public JLabel Player(int x, int y, int width, int height, Icon icono){
JLabel imagen = new JLabel(icono);
imagen.setLocation(x, y);
imagen.setSize(width, height);
return imagen;
}
(Это для создания нового проигрывателя)
У меня также есть класс client:
public class Cliente implements Runnable {
String host;
int puerto;
Player mensaje;
public Cliente(int purto, Player mensaje, String host){
this.puerto = purto;
this.mensaje = mensaje;
this.host = host;
}
@Override
public void run() {
DataOutputStream out;
try {
Socket sc = new Socket(host, puerto);
out = new DataOutputStream(sc.getOutputStream());
ObjectOutputStream objectOutputStream = new ObjectOutputStream(out);
objectOutputStream.writeObject(mensaje);
sc.close();
} catch (IOException ex) {
System.out.println(ex);
}
}
}
И я использую ObjectOutputStream, но в нем говорится, что это
«java.io.NotSerializableException: объекты.Проигрыватель»
И я хочу отправить свой плеер на сервер, но он говорит, что исключение!
Также, если вам нужен класс сервера
public class Servidor extends Observable implements Runnable {
int puerto;
public Servidor(int puerto) {
this.puerto = puerto;
}
@Override
public void run() {
ServerSocket servidor = null;
Socket sc = null;
DataInputStream in;
try {
servidor = new ServerSocket(puerto);
System.out.println("server started");
while (true) {
sc = servidor.accept();
in = new DataInputStream(sc.getInputStream());
ObjectInputStream input = new ObjectInputStream(in);
Player players = null;
try {
players = (Player) input.readObject();
System.out.println(players.Nombre);
} catch (ClassNotFoundException ex) {
}
this.setChanged();
this.notifyObservers(players);
this.clearChanged();
sc.close();
}
} catch (IOException ex) {
}
}
}
а также, если вы хотите, вот строки кода, которые отправляют запрос в клиентский класс
Cliente c = new Cliente(5000, new Player(x, y, width, height, icon, "name of the player"), "the ip");
Thread t = new Thread(c);
t.start();
Ответ №1:
Похоже, вы забыли сделать объект Player сериализуемым, поэтому код выбрасывается java.io.NotSerializableException
Если вам нужно отправить какой-либо объект по сети, тогда объект должен быть сериализуемым.
Сериализация — это процесс получения структуры данных объекта в памяти и кодирования ее в последовательную (отсюда и термин) последовательность байтов. Затем эта закодированная версия может быть сохранена на диске, отправлена по сетевому соединению или иным образом передана получателю. (из Wikipedia.org )
Я обновил код
Player.java
import java.io.Serializable;
import javax.swing.Icon;
import javax.swing.JLabel;
public class Player implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
public JLabel imagen;
public String Nombre;
public Player(int x, int y, int width, int height, Icon icono, String name) {
imagen = Player(x, y, width, height, icono);
Nombre = name;
}
public JLabel Player(int x, int y, int width, int height, Icon icono) {
JLabel imagen = new JLabel(icono);
imagen.setLocation(x, y);
imagen.setSize(width, height);
return imagen;
}
}
Cliente.java
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.Socket;
public class Cliente implements Runnable {
String host;
int puerto;
Player mensaje;
public Cliente(int purto, Player mensaje, String host) {
this.puerto = purto;
this.mensaje = mensaje;
this.host = host;
}
// @Override
public void run() {
DataOutputStream out;
try {
Socket sc = new Socket(host, puerto);
out = new DataOutputStream(sc.getOutputStream());
ObjectOutputStream objectOutputStream = new ObjectOutputStream(out);
objectOutputStream.writeObject(mensaje);
sc.close();
} catch (IOException ex) {
System.out.println(ex);
}
}
public static void main(String[] args) {
Cliente c = new Cliente(5000, new Player(1, 2, 3, 4, null,
"Holis Studios"), "localhost");
Thread t = new Thread(c);
t.start();
}
}
Servidor.java
import java.io.DataInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Observable;
public class Servidor extends Observable implements Runnable {
int puerto;
public Servidor(int puerto) {
this.puerto = puerto;
}
// @Override
public void run() {
ServerSocket servidor = null;
Socket sc = null;
DataInputStream in;
try {
servidor = new ServerSocket(puerto);
System.out.println("server started");
while (true) {
sc = servidor.accept();
in = new DataInputStream(sc.getInputStream());
ObjectInputStream input = new ObjectInputStream(in);
Player players = null;
try {
players = (Player) input.readObject();
System.out.println(players.Nombre);
} catch (ClassNotFoundException ex) {
}
this.setChanged();
this.notifyObservers(players);
this.clearChanged();
sc.close();
}
} catch (IOException ex) {
}
}
public static void main(String[] args) {
Servidor server = new Servidor(5000);
Thread t = new Thread(server);
t.start();
}
}
Компиляция кода:
javac.exe -cp . Player.java
javac.exe -cp . Servidor.java
javac.exe -cp . Cliente.java
Выполнить:
java.exe -cp . Servidor
server started
java.exe -cp . Cliente
Вывод, отображаемый на консоли Servidor:
server started
Holis Studios