I am having an issue figuring out how to keep a connection open with my server class. When it connects I want the client to send to the server that a client has connected, which it does. My issue is that right after it receives the message the java file stops running. Could anybody give me some advice on how to keep the Server waiting for a message from the user until a certain message is received? Thank you in advance, will be researching in the mean time.
Client class:
import java.io.*;
import java.net.*;
import java.util.*;
public class Client {
public static void main(String[] args) throws Exception
{
Client myClient = new Client();
myClient.run();
}
public void run() throws Exception
{
Socket clientSocket = new Socket("localhost", 9999);
PrintStream ps1 = new PrintStream(clientSocket.getOutputStream());
ps1.println("A client has successfully connected.");
//Sends message to the server
PrintStream ps = new PrintStream(clientSocket.getOutputStream());
Scanner scan = new Scanner(System.in);
String cMessage = scan.nextLine();
ps.println(cMessage);
//Reads and displays response from server
InputStreamReader ir = new InputStreamReader(clientSocket.getInputStream());
BufferedReader br = new BufferedReader(ir);
String message = br.readLine();
System.out.println(message);
}
}
Server class:
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) throws Exception
{
Server myServer = new Server();
myServer.run();
}
public void run() throws Exception
{
//Initializes the port the serverSocket will be on
ServerSocket serverSocket = new ServerSocket(9999);
System.out.println("The Server is waiting for a client on port 9999");
//Accepts the connection for the client socket
Socket socket = serverSocket.accept();
InputStreamReader ir = new InputStreamReader(socket.getInputStream());
BufferedReader br = new BufferedReader(ir);
String message = br.readLine();
//Confirms that the message was received
System.out.println(message);
if(message.equals("HELLO"))
{
PrintStream ps = new PrintStream(socket.getOutputStream());
ps.println("Received our hello message.");
}
else
{
PrintStream ps = new PrintStream(socket.getOutputStream());
ps.println("Did not receive your hello message");
}
}
}
use the while loop for continuouly running your server and compare the received message with the desired end message ( bye ) with the if condition, the code is given below,
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) throws Exception
{
Server myServer = new Server();
myServer.run();
}
public void run() throws Exception
{
//Initializes the port the serverSocket will be on
ServerSocket serverSocket = new ServerSocket(9999);
while(true)
{
System.out.println("The Server is waiting for a client on port 9999");
//Accepts the connection for the client socket
Socket socket = serverSocket.accept();
InputStreamReader ir = new InputStreamReader(socket.getInputStream());
BufferedReader br = new BufferedReader(ir);
String message = br.readLine();
//Confirms that the message was received
System.out.println(message);
if(message.equals("HELLO"))
{
PrintStream ps = new PrintStream(socket.getOutputStream());
ps.println("Received our hello message.");
}
else
{
PrintStream ps = new PrintStream(socket.getOutputStream());
ps.println("Did not receive your hello message");
}
}
if(message.equals("bye"))
break; // breaking the while loop.
} // end of while loop.
}
Related
I am playing around with networking and trying to send a simple message over my network using sockets in Java.
Here is the server code:
public class Server {
public static void main(String[] args) throws IOException {
String clientSentence;
String uppercaseSentence;
ServerSocket welcomeSocket = new ServerSocket(6789);
System.out.println("Server Running.");
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
clientSentence = inFromClient.readLine();
System.out.println("Client message received: " + clientSentence);
}
Here is the client code:
public class Client {
public static void main(String[] args) throws IOException {
String originalSentence;
String modifiedSentence;
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
Socket clientSocket = new Socket("localhost", 6789);
System.out.println("Please enter a sentence: ");
originalSentence = inFromUser.readLine();
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
outToServer.writeBytes(originalSentence);
System.out.println("Message Sent");
}
When I run them both and input a message into the client side, there is no confirmation on the side of the server in the console, however there is confirmation on the client side that a message has been sent. If I then end the client and stop it running, the server will output the sent message to the console them immediately throw an error.
I think it has something to do with the actual BufferedReader not actually getting the message or something?
Again I am very new to networking so any help would be much appreciated
Make sure that there is symmetry in how one connection sends data and how the other side receives the data. So, if the client is sending data via a DataOutputStream, then best to read the data in as a DataInputStream. If OTOH, you're only sending Strings, I would use a Writer such as a PrintWriter and then read with a Reader. I would send each line via println(...) and would call .flush() on the PrintWriter to ensure that the buffer sends the line when desired. For example, a simple client could look like so:
import java.util.*;
import java.net.*;
import java.io.*;
public class Client {
public static final String EXIT = "exit";
public static final int HOST_ID = 6789;
public static void main(String[] args) {
// using try-with-resources so that I close all streams when done
try (
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
Socket clientSocket = new Socket("localhost", HOST_ID);
PrintWriter out = new PrintWriter(clientSocket.getOutputStream());
) {
String input = "";
do {
System.out.print("Please enter a sentence, or \"exit\" to exit: ");
input = inFromUser.readLine();
out.println(input);
// flush the output stream to send all pending bites:
out.flush();
} while (!input.equalsIgnoreCase(EXIT));
System.out.println("All Done");
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
and the Server could look like:
import java.util.*;
import java.net.*;
import java.io.*;
public class Server {
public static void main(String[] args) {
// using try-with-resources so that I close all streams when done
try (
ServerSocket welcomeSocket = new ServerSocket(6789);
Scanner scanner = new Scanner(welcomeSocket.accept().getInputStream());
) {
System.out.println("Server Running.");
System.out.println("socket accepted");
while (scanner.hasNextLine()) {
String text = scanner.nextLine();
System.out.println("text: " + text);
System.out.println("uppercase: " + text.toUpperCase());
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
I have written server and client part, see code:
//this I run on my firt PC
public class TCPServer {
public static void main(String[] args) throws Exception{
TCPServer server = new TCPServer();
server.run();
}
public void run() throws Exception{
ServerSocket socket = new ServerSocket(6789);
Socket SOCK = socket.accept();
BufferedReader BR = new BufferedReader(new InputStreamReader(SOCK.getInputStream()));
String msg = BR.readLine();
System.out.println(msg);
if(msg != null){
PrintStream PS = new PrintStream(SOCK.getOutputStream());
PS.print("MESSAGE RECEIVED");
}
}
}
//This I run on my notebook
public class TCPClient {
public static void main(String args[]) throws Exception{
TCPClient client = new TCPClient();
client.run();
}
public void run() throws Exception{
Socket clientSocket = new Socket("192.168.88.77",6789);
PrintStream PS = new PrintStream(clientSocket.getOutputStream());
PS.print("Hello from GLADIS VLADLEN");
BufferedReader BR = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String msg = BR.readLine();
System.out.println(msg);
}
}
After running this applications nothing happens. And only after I stop Client app message is received by server part. Why this happens? I try to turn off FireWall but this don't help me.
Both the server and client are reading a line using BufferedReader#readLine(). However the PrintStream is sending characters without the line terminator.
Try calling println instead of print.
Recently I was looking at socket communications, and after I read few tutorials I came out with something like that.
public class Server{
public static void main(String[] args) throws IOException, InterruptedException {
ServerSocket server = new ServerSocket(9999);
Socket socket = server.accept();
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String message = "";
int ch = -1;
while((ch=in.read())!= -1 ){
message+=ch;
}
// String message = in.readLine();
System.out.println("RECEIVED "+message);
out.write("RESPONSE "+message+"\n");
out.flush();
System.out.println("NEW MESSAGE SEND");
Thread.sleep(3000);
System.out.println("CLOSE");
server.close();
}
}
public class Client {
public static void main(String[] args) throws UnknownHostException, IOException {
Socket socket = new Socket("127.0.0.1", 9999);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
out.write("MESSAGE\n");
out.flush();
System.out.println("SEND MESSAGE");
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
System.out.println(in.readLine());
socket.close();
}
}
After I run this code, Client logs "SEND MESSAGE" while server hangs on in.read() and does not receiving any message.
Can anyone help me and explain me what I'm doing wrong?
Your server is reading from the socket until end of stream. End of stream only occurs when the peer closes the connection. At that point you will be unable to send a reply. You need to reconsider your protocol. For a simple example you could read and write lines, one at a time, as you are in the client.
I have a program ready that acts as a client and another that acts as a server.
I want to be able to send a message to the server, and the server will then forward the message to another client that is also connected to the server.
So the the server is supposed to forward the message to the other client.
How would i be able to do that, and what do I need to read up on?
This is what i got now.
Server.java
package server;
import java.net.*;
import java.io.*;
import javax.swing.*;
public class Server{
public static void run() {
ServerSocket serverSocket = null;
Socket socket = null;
try{
while(true){
serverSocket = new ServerSocket(5555);
socket = serverSocket.accept();
InputStreamReader streamReader = new InputStreamReader(socket.getInputStream());
BufferedReader bufferedReader = new BufferedReader(streamReader);
String message = bufferedReader.readLine();
System.out.println(message);
if(message != null){
PrintStream printStream = new PrintStream(socket.getOutputStream());
printStream.println("Message receivd!");
}
streamReader.close();
socket.close();
serverSocket.close();
bufferedReader.close();
}
}catch(Exception e){}
// try{
//
// }catch(Exception e){}
}
public static void main(String[]args){
Server s = new Server();
s.run();
}
}
And then I also got TCPClient.java
package client;
import java.net.*;
import java.io.*;
public class TCPClient {
private String serverIP = "localhost";
private int serverPort = 1111;
private int count = 0;
private Thread thread;
public TCPClient() {
this.thread = new Thread(new ConnectAndListenToServer());
// thread.start();
}
public void sendMessage(int count){
this.count = count;
this.thread = new Thread(new ConnectAndListenToServer());
thread.start();
}
private class ConnectAndListenToServer implements Runnable {
Socket socket = null;
public void run() {
BufferedReader bufferedReader = null;
InputStreamReader streamReader = null;
try {
socket = new Socket(serverIP,serverPort);
PrintStream printStream = new PrintStream(socket.getOutputStream());
printStream.println(count);
streamReader = new InputStreamReader(socket.getInputStream());
bufferedReader = new BufferedReader(streamReader);
String message = bufferedReader.readLine();
if(message != null){
System.out.println(message);
}
}catch(Exception e){}
try{
socket.close();
bufferedReader.close();
streamReader.close();
}catch(Exception ee){}
}
}
}
How would i be able to forward the messeage already received on the server to another client?
How would i be able to forward the messeage already received on the server to another client?
I have already posted some samples in the same context.
Till now you have done well, to complete it please have a look Client-Server Communication. I have described it step by step just follow the thread to find other samples as well.
Please let me know if still you have any issue!
This just works if you have Client 2 connected while Client 1 is also connected.
This is possible if you write a multithreading application or use a Selector.
My Issue based on code below:
Run TCPServer.java
then Run TCPClient.java
I expect to have the client print out
Server Said(1): HEY DUDE 1
Server Said(2): HEY DUDE 2
... but it just stays on HEY DUDE 1. What am I doing that is not producing the results I want?
TCPServer.java
import java.io.*;
import java.net.*;
class TCPServer {
public static void main (String args[]) throws Exception{
new TCPServer();
}
TCPServer() throws Exception{
//create welcoming socket at port 6789
ServerSocket welcomeSocket = new ServerSocket(6789);
while (true) {
//block on welcoming socket for contact by a client
Socket connectionSocket = welcomeSocket.accept();
// create thread for client
Connection c = new Connection(connectionSocket);
}
}
class Connection extends Thread{
Socket connectionSocket;
Connection(Socket _connectionSocket){
connectionSocket = _connectionSocket;
this.start();
}
public void run(){
try{
//create input stream attached to socket
BufferedReader inFromClient = new BufferedReader(new InputStreamReader (connectionSocket.getInputStream()));
//create output stream attached to socket
PrintWriter outToClient = new PrintWriter(new OutputStreamWriter(connectionSocket.getOutputStream()));
//read in line from the socket
String clientSentence = inFromClient.readLine();
System.out.println("Client sent: "+clientSentence);
//process
String capitalizedSentence = clientSentence.toUpperCase() + '\n';
//write out line to socket
outToClient.print(capitalizedSentence);
outToClient.flush();
}catch(Exception e){}
}
}
}
TCPClient.java
import java.io.*;
import java.net.*;
class TCPClient {
//String name="";
String host = "localhost";
int port = 6789;
Socket socket = null;
public static void main(String args[]) throws Exception{
TCPClient client = new TCPClient();
client.SendToServer("Hey dude 1");
System.out.println("Server Said(1): "+client.RecieveFromServer());
client.SendToServer("Hey dude 2");
System.out.println("Server Said(2): "+client.RecieveFromServer());
client.close();
}
TCPClient(String _host, int _port) throws Exception{
host = _host;
port = _port;
socket = new Socket(host, port);
}
TCPClient() throws Exception{
socket = new Socket(host, port);
}
void SendToServer(String msg) throws Exception{
//create output stream attached to socket
PrintWriter outToServer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
//send msg to server
outToServer.print(msg + '\n');
outToServer.flush();
}
String RecieveFromServer() throws Exception{
//create input stream attached to socket
BufferedReader inFromServer = new BufferedReader(new InputStreamReader (socket.getInputStream()));
//read line from server
String res = inFromServer.readLine(); // if connection closes on server end, this throws java.net.SocketException
return res;
}
void close() throws IOException{
socket.close();
}
}
Your server thread ends as soon as you process first message. You need to put server code into a loop like this:
String clientSentence;
while ((clientSentence = inFromClient.readLine()) != null) {
System.out.println("Client sent: "+clientSentence);
//process
String capitalizedSentence = clientSentence.toUpperCase() + '\n';
//write out line to socket
outToClient.print(capitalizedSentence);
outToClient.flush();
}