DylanG1991
DylanG1991

Reputation: 101

Connecting to a server via Java Socket and ServerSocket Class

I have what will hopefully be a very simple question. I'm writing a series of java programs which utilize cryptographic functions like RSA, El Gamal, etc for a security class. so that a client (Alice) and server (Bob) can communicate securely. But, I have no clue how to connect to a server on my computer using java. I've used MAMP to connect to a web server where I've written code in PHP/SQL, but I don't know how it would work using Java. Specifically, the starter files I was given all use the Java class Socket and ServerSocket like so:

String host = "localhost";
int port = 7999;
Socket s = new Socket(host, port);
ObjectOutputStream os = new ObjectOutputStream(s.getOutputStream());

And for the server (Bob):

int port = 7999;
ServerSocket s = new ServerSocket(port);
Socket client = s.accept();
ObjectInputStream is = new ObjectInputStream(client.getInputStream());

What would I do on my computer to connect to a server via this code?

Upvotes: 1

Views: 4771

Answers (1)

jason120
jason120

Reputation: 94

Client.java

import java.io.*;
import java.net.*;

public class Client {

    public static void main(String[] args) throws Exception {

        String host = "localhost";
        int port = 7999;
        Socket s = new Socket(host, port);
        ObjectOutputStream os = new ObjectOutputStream(s.getOutputStream());

        os.writeObject("Hello World");
        os.close();
    }

}

Server.java

import java.io.*;
import java.net.*;

public class Server {

    public static void main(String[] args) throws Exception {

        int port = 7999;
        ServerSocket s = new ServerSocket(port);
        Socket client = s.accept();
        ObjectInputStream is = new ObjectInputStream(client.getInputStream());

        String str = (String)is.readObject();

        System.out.println("Read string: " + str);

        is.close();
    }

}

Compile with

javac Client.java

and

javac Server.java

Run the server (you can test this running both on the same machine.)

java Server

Run the client (in another terminal or DOS prompt.)

java Client

On the server you should see:

server$ java Server 
Read string: Hello World
server$ 

Upvotes: 2

Related Questions