- Русские Блоги
- Передача Java-объекта через сокет (сериализация объекта)
- chatton / SendObjectsOverSockets.java
- Java Socket Programming-Transferring of Java Objects through sockets
- Transferring of Java Objects through sockets
- Student.java
- output of Client.java
- output of Server.java
- Significance of serialVersionUID
- See also:
- Computer Revolution (www.comrevo.com)
- How to send any java Object through socket?
Русские Блоги
Передача Java-объекта через сокет (сериализация объекта)
Эта статья в основном реализует j: передачу Java-объектов через сокеты. Используемый метод — сериализация объекта. Метод: через сокет
• установить соединение c / s, читать и записывать объекты через ObjectOutputStream, ObjectOutputStream. Единственное, на что стоит обратить внимание, это пройденная Java
Объект должен реализовывать интерфейс Serializable mark.
package com.yt.manager.Serializable; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.ServerSocket; import java.net.Socket; /** * @ Описание: сокет на стороне сервера * @ClassName: Server * @Project: base-info * @Author: zxf * @Date: 2011-7-15 */ public class Server < public static void main(String[] args) < ServerSocket serverSocket = null; Socket socket = null; ObjectInputStream objInputStream = null; ObjectOutputStream objOutputStream = null; try < serverSocket = new ServerSocket(11111); System.out.println («Служба сервера запущена . »); socket = serverSocket.accept(); // Десериализация объектов, написанных клиентом с использованием ObjectOutputStream objInputStream = new ObjectInputStream(socket.getInputStream()); Customer cusotmer = (Customer) objInputStream.readObject(); cusotmer.setName ("Hello:" + cusotmer.getName ()); objOutputStream = new ObjectOutputStream(socket.getOutputStream()); objOutputStream.writeObject(cusotmer); >catch (Exception e) < e.printStackTrace(); >finally < try < serverSocket.close(); socket.close(); >catch (IOException e) < e.printStackTrace(); >> > >
package com.yt.manager.Serializable; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.ServerSocket; import java.net.Socket; /** * @ Описание: сокет на стороне сервера * @ClassName: Server * @Project: base-info * @Author: zxf * @Date: 2011-7-15 */ public class Server < public static void main(String[] args) < ServerSocket serverSocket = null; Socket socket = null; ObjectInputStream objInputStream = null; ObjectOutputStream objOutputStream = null; try < serverSocket = new ServerSocket(11111); System.out.println («Служба сервера запущена . »); socket = serverSocket.accept(); // Десериализация объектов, написанных клиентом с использованием ObjectOutputStream objInputStream = new ObjectInputStream(socket.getInputStream()); Customer cusotmer = (Customer) objInputStream.readObject(); cusotmer.setName ("Hello:" + cusotmer.getName ()); objOutputStream = new ObjectOutputStream(socket.getOutputStream()); objOutputStream.writeObject(cusotmer); >catch (Exception e) < e.printStackTrace(); >finally < try < serverSocket.close(); socket.close(); >catch (IOException e) < e.printStackTrace(); >> > >
package com.yt.manager.Serializable; import java.io.Serializable; /** * @Description: реализовать интерфейс сериализации * @ClassName: Customer * @Project: base-info * @Author: zxf * @Date: 2011-5-30 */ public class Customer implements Serializable < private static final long serialVersionUID = 1L; public String name; public int age; public String getName() < return name; >public void setName(String name) < this.name = name; >public int getAge() < return age; >public void setAge(int age) < this.age = age; >>
chatton / SendObjectsOverSockets.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
import java . io . Serializable ; |
// must implement Serializable in order to be sent |
public class Message implements Serializable |
private final String text ; |
public Message ( String text ) |
this . text = text ; |
> |
public String getText () |
return text ; |
> |
> |
import java . io .*; |
import java . net . Socket ; |
import java . util . ArrayList ; |
import java . util . List ; |
public class Client |
public static void main ( String [] args ) throws IOException |
// need host and port, we want to connect to the ServerSocket at port 7777 |
Socket socket = new Socket ( «localhost» , 7777 ); |
System . out . println ( «Connected!» ); |
// get the output stream from the socket. |
OutputStream outputStream = socket . getOutputStream (); |
// create an object output stream from the output stream so we can send an object through it |
ObjectOutputStream objectOutputStream = new ObjectOutputStream ( outputStream ); |
// make a bunch of messages to send. |
List < Message >messages = new ArrayList <>(); |
messages . add ( new Message ( «Hello from the other side!» )); |
messages . add ( new Message ( «How are you doing?» )); |
messages . add ( new Message ( «What time is it?» )); |
messages . add ( new Message ( «Hi hi hi hi.» )); |
System . out . println ( «Sending messages to the ServerSocket» ); |
objectOutputStream . writeObject ( messages ); |
System . out . println ( «Closing socket and terminating program.» ); |
socket . close (); |
> |
> |
import java . io .*; |
import java . net . ServerSocket ; |
import java . net . Socket ; |
import java . util . List ; |
public class Server |
public static void main ( String [] args ) throws IOException , ClassNotFoundException |
// don’t need to specify a hostname, it will be the current machine |
ServerSocket ss = new ServerSocket ( 7777 ); |
System . out . println ( «ServerSocket awaiting connections. » ); |
Socket socket = ss . accept (); // blocking call, this will wait until a connection is attempted on this port. |
System . out . println ( «Connection from » + socket + «!» ); |
// get the input stream from the connected socket |
InputStream inputStream = socket . getInputStream (); |
// create a DataInputStream so we can read data from it. |
ObjectInputStream objectInputStream = new ObjectInputStream ( inputStream ); |
// read the list of messages from the socket |
List < Message >listOfMessages = ( List < Message >) objectInputStream . readObject (); |
System . out . println ( «Received [» + listOfMessages . size () + «] messages from: » + socket ); |
// print out the text of every message |
System . out . println ( «All messages:» ); |
listOfMessages . forEach (( msg )-> System . out . println ( msg . getText ())); |
System . out . println ( «Closing sockets.» ); |
ss . close (); |
socket . close (); |
> |
> |
// Server output |
/* |
ServerSocket awaiting connections. |
Connection from Socket[addr=/127.0.0.1,port=62360,localport=7777]! |
Received [4] messages from: Socket[addr=/127.0.0.1,port=62360,localport=7777] |
All messages: |
Hello from the other side! |
How are you doing? |
What time is it? |
Hi hi hi hi. |
Closing sockets. |
*/ |
// Client output |
/* |
Connected! |
Sending messages to the ServerSocket |
Closing socket and terminating program. |
*/ |
Java Socket Programming-Transferring of Java Objects through sockets
So far we discussed about the fundamentals of networking with Java.We have seen sample codes for TCP and UDP communications.If there is a provision to transfer a Java object between two jVMs through sockets ,it would be a greater advantage to developers.Fortunately , Java allows transferring of objects through sockets. The only thing the developer needs to be taken care is : the class whose object needs to be transferred should implement the Serializable interface . We already discussed the importance of Serializable interface when we discussed the object serialization . In this section , we are discussing how the transferring of Java objects through sockets is happening , with a suitable example.Here , we are explaining with TCP sockets.
Transferring of Java Objects through sockets
Assume we have a client application in one machine and a server application in another machine.And we need to transfer a Student object from client to server.So our Student.java should implement the Serializable interface .
Student.java
public class Student implements Serializable
private static final long serialVersionUID = 5950169519310163575L;
private int id;
private String name;
public Student(int id, String name) this.id = id;
this.name = name;
>
public int getId() return id;
>
public void setId(int id) this.id = id;
>
public String getName() return name;
>
public void setName(String name) this.name = name;
>
public boolean equals(Object o) if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
if (id != student.id) return false;
if (name != null ? !name.equals(student.name) : student.name != null) return false;
public int hashCode() return id;
>
public String toString() return «Id = » + getId() + » ; Name text-decoration: underline;»>Client.java
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.SocketException;
public class Client private Socket socket = null;
private ObjectInputStream inputStream = null;
private ObjectOutputStream outputStream = null;
private boolean isConnected = false;
while (!isConnected) try socket = new Socket(«localHost», 4445);
System.out.println(«Connected»);
isConnected = true;
outputStream = new ObjectOutputStream(socket.getOutputStream());
Student student = new Student(1, «Bijoy»);
System.out.println(«Object to be written text-decoration: underline;»>Server.java
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
public class Server private ServerSocket serverSocket = null;
private Socket socket = null;
private ObjectInputStream inStream = null;
public void communicate() try serverSocket = new ServerSocket(4445);
socket = serverSocket.accept();
System.out.println(«Connected»);
inStream = new ObjectInputStream(socket.getInputStream());
Student student = (Student) inStream.readObject();
System.out.println(«Object received text-decoration: underline;»>Output
Run Server.java and Client.java
output of Client.java
Object to be written = ; Name = Bijoy
output of Server.java
Object received = ; Name = Bijoy
Significance of serialVersionUID
While performing the operation of sending serialized object through socket , the serialVersionUID is very important. Our client and server applications should have the class with same serialVersionUID.In other words , the correct version of class should be there in client and server.Otherwise java.io.InvalidClassException will be thrown.We can verify the result by simply changing the serialVersionUID of Student.java in client side and server side with unmatched values.
See also:
Computer Revolution (www.comrevo.com)
In previous post https://www.comrevo.com/2017/08/serialization-in-java-with-example.html, we have seen
What is Serialization?
What is the need of Serialization?
What is Deserialization?
How to achieve Serialization?
class Sample implements Serializable
String name;
String city;
String contactnum;
>
public class SerializationClient
public static void main(String[] args) throws Exception
Sample obj=new Sample();
obj.name=»Ramesh»;
obj.city=»Pune»;
obj.contactnum=»9090909090″;
Socket socket = new Socket(«localhost», 7000);
System.out.println(«Connected»);
//Serialization
OutputStream os = socket.getOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(os);
System.out.println(«Sending values to the ServerSocket»);
oos.writeObject(obj);
parag@parag-Inspiron-N4010:~/Desktop/programs/socket$ java SerializationClient
Connected
Sending values to the ServerSocket
Closing socket and terminating program.
class Sample implements Serializable
String name;
String city;
String contactnum;
>
public class SerializationServer
public static void main(String[] args) throws Exception
ServerSocket ss = new ServerSocket(7000);
System.out.println(«ServerSocket awaiting connections. «);
Socket socket = ss.accept();
System.out.println(«Connection from » + socket);
//Deserialization
InputStream is = socket.getInputStream();
ObjectInputStream ois = new ObjectInputStream(is);
Sample obj1=(Sample)ois.readObject();
System.out.println(«Values received from Client are:-«);
System.out.println(«Name:»+obj1.name);
System.out.println(«City:»+obj1.city);
System.out.println(«Contact No.:»+obj1.contactnum);
parag@parag-Inspiron-N4010:~/Desktop/programs/socket$ java SerializationServer
ServerSocket awaiting connections.
Connection from Socket[addr=/127.0.0.1,port=41350,localport=7000]Values received from Client are:-
Name:Ramesh
City:Pune
Contact No.:9090909090
Closing sockets.
How to send any java Object through socket?
posted 21 years ago
Hi Everybody,
I want know how to send any java Object through socket i.e. send Object through socket from client side and read it to the server side and vice versa.
Please suggest solution me.
Regards From Parshuram
posted 21 years ago
To send an object thru a stream you need to serialize it ie.. the object should implement the serializable interface; this is a ‘marker’ interface hence you dont need to define any methods.
All objects that support the java.io.Serializable interface can be written to streams.
TO send the object you use an ObjectOutputStream — call its writeObject method, Likewise to read you use the ObjectInputStream’s readObject method.
Hope the code below helps —
[ February 04, 2002: Message edited by: Les Dsouza ]