Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save mo7amd89/079c1f7c7cc530e9fd2bd197d98702e2 to your computer and use it in GitHub Desktop.
Save mo7amd89/079c1f7c7cc530e9fd2bd197d98702e2 to your computer and use it in GitHub Desktop.
Example of sending a String through a Socket in Java.
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
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 a data output stream from the output stream so we can send data through it
DataOutputStream dataOutputStream = new DataOutputStream(outputStream);
System.out.println("Sending string to the ServerSocket");
// write the message we want to send
dataOutputStream.writeUTF("Hello from the other side!");
dataOutputStream.flush(); // send the message
dataOutputStream.close(); // close the output stream when we're done.
System.out.println("Closing socket and terminating program.");
socket.close();
}
}
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) throws IOException {
// 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.
DataInputStream dataInputStream = new DataInputStream(inputStream);
// read the message from the socket
String message = dataInputStream.readUTF();
System.out.println("The message sent from the socket was: " + message);
System.out.println("Closing sockets.");
ss.close();
socket.close();
}
}
//Server Output
/*
ServerSocket awaiting connections...
Connection from Socket[addr=/127.0.0.1,port=62085,localport=7777]!
The message sent from the socket was: Hello from the other side!
Closing sockets.
*/
// Client Output
/*
Connected!
Sending string to the ServerSocket
Closing socket and terminating program.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment