Skip to content

Instantly share code, notes, and snippets.

@chatton
Created September 26, 2017 15:27
Show Gist options
  • Star 54 You must be signed in to star a gist
  • Fork 7 You must be signed in to fork a gist
  • Save chatton/14110d2550126b12c0254501dde73616 to your computer and use it in GitHub Desktop.
Save chatton/14110d2550126b12c0254501dde73616 to your computer and use it in GitHub Desktop.
Example of how to send an Object over a Socket in Java.
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.
*/
@cordsac
Copy link

cordsac commented Apr 12, 2019

Should I need to add Student class in both applications? I'm not clear that point

@omandotkom
Copy link

this is absolutely working for me

@JOSUERV99
Copy link

Is working

@nicolasmanurung
Copy link

Thank you... It's work

@moulayprogrammer
Copy link

Thank you ...

Copy link

ghost commented Apr 24, 2020

Just curious, 'msg' isn't defined so that was confusing.

@trinhvandat
Copy link

Hello guys! Thanks for your code. But I want create 1 server and two client. One client is supported publish message, other client is supported receive message. But when I run server, I can only run 1 client connected to it.

@JGornas
Copy link

JGornas commented Oct 22, 2020

Thank you! The code was useful to me.

@Sclafus
Copy link

Sclafus commented Nov 29, 2020

Thanks, this was really useful!

@PatrickNiyogitare28
Copy link

Hi! It worked, kudos

@wardpl2
Copy link

wardpl2 commented Dec 8, 2021

@trinhvandat You would need to create 2 Sockets in your Server class so that it can handle 2 clients connecting to it. In general, in your server class, you should create as many Sockets as there are clients that are going to be connecting to it.

@ugu11
Copy link

ugu11 commented Jan 3, 2022

thank u bro

@Tsireledzo2
Copy link

what if I want to send more than one variable from the object class?
what must I do

@Tsireledzo2
Copy link

and are these classes in different projects? or are in one project?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment