Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
I developed a Chat Server and client using Sockets and everything has been fine until I read somewhere online that ordinary Socket communication is vulnerable to attacks. After googling a while, I came across this page that showed a sample SSLServerSocket and SSLSocket implementation (code below).
I will like to know if the communication between my server and client is secure if I follow steps in the below code.
Server Code
class EchoServer {
public static void main(String[] args) throws IOException {
SSLServerSocket sslServerSocket = null;
try {
SSLServerSocketFactory sslServerSocketFactory = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
sslServerSocket = (SSLServerSocket) sslServerSocketFactory.createServerSocket(9999);
SSLSocket sslSocket = (SSLSocket) sslServerSocket.accept();
PrintWriter out = new PrintWriter(sslSocket.getOutputStream(),true);
BufferedReader in = new BufferedReader(new InputStreamReader(sslSocket.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
out.println(inputLine);
}
} finally {
if (sslServerSocket != null) {
try {
sslServerSocket.close();
} catch (IOException x) {
// handle error
}
}
}
}
}
Client Code
class EchoClient {
public static void main(String[] args) throws IOException {
SSLSocket sslSocket = null;
try {
SSLSocketFactory sslSocketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
sslSocket = (SSLSocket) sslSocketFactory.createSocket("localhost", 9999);
PrintWriter out = new PrintWriter(sslSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(sslSocket.getInputStream()));
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String userInput;
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
System.out.println(in.readLine());
}
} finally {
if (sslSocket != null) {
try {
sslSocket.close();
} catch (IOException x) {
// handle error
}
}
}
}
}
You should get the peer certificate via a HandshakeCompletionListener or the SSLSession to verify that you're talking to the host you think you're talking to. Other than that your code is OK from the security point of view.
However you should also be aware that you shouldn't use PrintWriter over a network, as it swallows exceptions.
Related
I'm reading through the KnockKnockServer example:
import java.net.*;
import java.io.*;
public class KnockKnockServer {
public static void main(String[] args) throws IOException {
if (args.length != 1) {
System.err.println("Usage: java KnockKnockServer <port number>");
System.exit(1);
}
int portNumber = Integer.parseInt(args[0]);
try (
ServerSocket serverSocket = new ServerSocket(portNumber);
Socket clientSocket = serverSocket.accept();
PrintWriter out =
new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
) {
String inputLine, outputLine;
// Initiate conversation with client
KnockKnockProtocol kkp = new KnockKnockProtocol();
outputLine = kkp.processInput(null);
out.println(outputLine);
while ((inputLine = in.readLine()) != null) {
outputLine = kkp.processInput(inputLine);
out.println(outputLine);
if (outputLine.equals("Bye."))
break;
}
} catch (IOException e) {
System.out.println("Exception caught when trying to listen on
port" + portNumber + " or listening for a connection");
System.out.println(e.getMessage());
}
}
}
My question regards exception handling. Firstly, why does the main method/function have a throws clause associated with it? To my knowledge any IOException will be dealt with in the corresponding catch block and not forwarded up the chain.
Secondly, it is my understanding that accepting a socket connection, and attempting to read from an active/created connection may throw IOExceptions. Is it better to try and handle acceptance of the connection separately from attempts to read from it, or is this particular style "kosher"?
Hello programmers on the internet. I am currently stepping through an operating systems book and there are some exercises that involve the following pieces of code.
This is the server code
import java.net.*;
import java.io.*;
public class DateServer{
public static void main(String[] args) {
try {
ServerSocket sock = new ServerSocket(6013);
// now listen for connections
while (true) {
Socket client = sock.accept();
PrintWriter pout = new
PrintWriter(client.getOutputStream(), true);
// write the Date to the socket
pout.println(new java.util.Date().toString());
// close the socket and resume
// listening for connections
client.close();
}
}
catch (IOException ioe) {
System.err.println(ioe);
}
}
}
This is the client code
import java.net.*;
import java.io.*;
public class DateClient{
public static void main(String[] args) {
try {
//make connection to server socket
Socket sock = new Socket("127.0.0.1",6013);
InputStream in = sock.getInputStream();
BufferedReader bin = new
BufferedReader(new InputStreamReader(in));
// read the date from the socket
String line;
while ( (line = bin.readLine()) != null)
System.out.println(line);
// close the socket connection
sock.close();
}
catch (IOException ioe) {
System.err.println(ioe);
}
}
}
So to my understanding the server is creating a socket and writing a date value to it. The client is then coming a long and connecting to the server and writing out the value in that socket. Am I interpreting this code correctly? This is my first experience with sockets.
Now for my actual question. I want to have the client connect to the server (and print out a message saying you are connected) and then be able to send a value over to the server so that the server can process it. How would I go about doing this? I have tried tinkering with DataOutputStream and DataInputStream but I have never used either before. Any help would be GREATLY appreciated.
You are correct. You have the server writing to the socket and the client reading from the socket. You want to reverse that.
Server Should look like:
ServerSocket sock = new ServerSocket(6013);
// now listen for connections
while (true)
{
Socket client = sock.accept();
InputStream in = client.getInputStream();
BufferedReader bin = new BufferedReader(new InputStreamReader(in));
// read the date from the client socket
String line;
while ((line = bin.readLine()) != null)
System.out.println(line);
// close the socket connection
client.close();
}
The client should look like:
try
{
// make connection to server socket
Socket sock = new Socket("127.0.0.1", 6013);
PrintWriter out = new PrintWriter(sock.getOutputStream(), true);
// send a date to the server
out.println("1985");
sock.close();
}
catch (IOException ioe)
{
System.err.println(ioe);
}
I'm trying to write an echo client server but I do not get any response from the server. Don't know where my mistakes are.
I've seen some examples on the internet. Some just use InputStream/OutputStream but I decided to use BufferedReader and PrintWriter - does this make any big differences?
Server side:
public class Server {
public static void main(String[] args){
Server server = new Server();
server.runServer(Integer.parseInt(args[0]));
}
private void runServer(final int port){
ServerSocket serversckt = null;
Socket socket = null;
BufferedReader in = null;
PrintWriter out = null;
try{
serversckt = new ServerSocket(port);
socket = serversckt.accept();
System.out.println("Request from client accepted!");
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);
String str;
while((str = in.readLine()) != null){
System.out.println(str);
out.println(str);
out.flush();
}
}
catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
Client side:
public class Client{
public static void main(String[] args){
Client client = new Client();
client.runClient(Integer.parseInt(args[0]), args[1]);
}
private void runClient(final int port, final String hostname){
Socket sckt = null;
try{
sckt = new Socket(hostname, port);
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
BufferedReader in = new BufferedReader(new InputStreamReader(sckt.getInputStream()));
PrintWriter out = new PrintWriter(sckt.getOutputStream(), true);
String str;
while((str = stdIn.readLine()) != null){
out.println(str);
System.out.println(in.readLine());
}
} catch(IOException e){
System.out.println(e.getMessage());
}
}
Thanks!
I'm unable to reproduce your problem. I added the missing imports and the final } in Client.java, compiled, and ran the server and client in different terminals.
Client:
$ java Client 2000 localhost
foo
foo
bar
bar
Server:
$ java Server 2000
Request from client accepted!
foo
bar
Every time I wrote something in the client window, it was echoed back to me, and the same line showed up on the server.
I want to write a client-sever program in which server and client send messages to each other. First, my server send a message to client, then the client reply. Next, my server send another message, the client reply. The problem is, on my first message induced by the server, the client does not respond.
My server:
public class Server {
public void go() {
try {
ServerSocket serverSocket = new ServerSocket(9999);
System.out.println("Server listening ...");
Socket socket = serverSocket.accept();
try (
PrintWriter printWriter = new PrintWriter(socket.getOutputStream());
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
) {
String input;
printWriter.println(new Scanner(System.in).nextLine());
while ((input = bufferedReader.readLine()) != null) {
System.out.println(input);
printWriter.println(new Scanner(System.in).nextLine());
if(input == "Bye") break;
}
}
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
public static void main(String[] args) {
Server server = new Server();
server.go();
}
}
My client:
public class Client {
public void go() {
try {
try (
Socket socket = new Socket("localhost", 9999);
PrintWriter printWriter = new PrintWriter(socket.getOutputStream());
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
) {
String input;
while ((input = bufferedReader.readLine()) != null) {
System.out.println("1");
System.out.println(input);
printWriter.println(new Scanner(System.in).nextLine());
}
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Client client = new Client();
client.go();
}
}
Are there some problems with my code?
Your client connects and then blocks reading a line from the server.
Your server accepts the connection and then blocks reading a line from the client.
I don't know what you were expecting to happen next, but it won't. Somebody needs to send something.
Your code seems to be fine. You just need to push the infrastructure by calling flush() after writing:
printWriter.flush();
Hi I am trying to understand how Sockets work can implement a multiplayer side to a monopoly game.I understood how to create the connection, but now it seems I have trouble sending and receiving the data between the client and the server .Here is my code:
Client code:
public class EchoClient
{
public static void main(String[] args)
{
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try
{
echoSocket = new Socket("127.0.0.1", 5000);;
out = new PrintWriter(echoSocket.getOutputStream());
in = new BufferedReader(
new InputStreamReader(echoSocket.getInputStream()));
BufferedReader stdIn = new BufferedReader(
new InputStreamReader(System.in));
String userInput;
while ((userInput = stdIn.readLine()) != null)
{
out.println(userInput);
}
out.close();
in.close();
stdIn.close();
echoSocket.close();
}
catch (UnknownHostException e)
{
System.err.println("Don't know about host: taranis");
}
catch (IOException e)
{
System.err.println("Couldent get I/O for "
+ " the connection to : taranis.");
}
}
}
Server code:
public class ServerSide
{
ServerSocket connect;
Socket connection;
PrintWriter out;
BufferedReader in;
public void go()
{
try
{
connect = new ServerSocket(5000);
connection = connect.accept();
in = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
String userInput;
while ((userInput = in.readLine()) != null)
{
System.out.println("echo: " + in.readLine());
}
}
catch (IOException e)
{
System.out.println(e);
}
}
public static void main(String[] args)
{
new ServerSide().go();
}
}
I was trying to create here a simple connection between a client and a server.On the client side when the user inputs data I want it to be sent to the server and then print it it on the server console.It seems that the way I wright the code it isent working what did I do wrong?
First of all you need to declare a console object and then print on it.
Then don't forget to:
After every print on the console at the server side you need to flush the stream so the all the data will be printed.
Your code looks fine to me. Usually with sockets and keyboard input, you run into the case where the reader.readLine() hangs because it is still trying to read input from the other side. Typically, i will put an empty out.println() at the end of my client so the server will terminate the reading while loop. I've tried flush() before as Mike suggested but that seems to not work for me.
On the client, you're missing out.flush; after the out.println.
On the server,
while ((userInput = in.readLine()) != null) {
System.out.println("echo: " + userInput); // not in.readLine
}