I'm new to Java programming and I'm just trying to get a very basic networking program to work.
I have 2 classes, a client and a server. The idea is the client simply sends a message to the server, then the server converts the message to capitals and sends it back to the client.
I'm having no issues getting the server to send a message to the client, the problem is I can't seem to store the message the client is sending in a variable server side in order to convert it and so can't send that specific message back.
Here's my code so far:
SERVER SIDE
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket (9091);
while (true) {
System.out.println("Waiting");
//establish connection
Socket client = server.accept();
System.out.println("Connected " + client.getInetAddress());
//create IO streams
DataInputStream inFromClient = new DataInputStream(client.getInputStream());
DataOutputStream outToClient = new DataOutputStream(client.getOutputStream());
System.out.println(inFromClient.readUTF());
String word = inFromClient.readUTF();
outToClient.writeUTF(word.toUpperCase());
client.close();
}
}
}
CLIENT SIDE
public class Client {
public static void main(String[] args) throws IOException {
Socket server = new Socket("localhost", 9091);
System.out.println("Connected to " + server.getInetAddress());
//create io streams
DataInputStream inFromServer = new DataInputStream(server.getInputStream());
DataOutputStream outToServer = new DataOutputStream(server.getOutputStream());
//send to server
outToServer.writeUTF("Message");
//read from server
String data = inFromServer.readUTF();
System.out.println("Server said \n\n" + data);
server.close();
}
}
I think the problem might be with the 'String word = inFromClient.readUTF();' line? Please can someone advise? Thanks.
You're discarding the first packet received from the client:
System.out.println(inFromClient.readUTF()); // This String is discarded
String word = inFromClient.readUTF();
Why not swap these?
String word = inFromClient.readUTF(); // save the first packet received
System.out.println(word); // and also print it
Related
I am running a client server program on port 80 (currently says port 2040 for testing purposes only). Whenever I run my server on my client side/browser, the console displays this weird text, when it should be returning a HTMl file that i scannned in. However, when I run my IP address on my browser, it returns the necessary code. Why?
Here is my code:
public class ServerSide {
public static void main(String[] args) throws Exception {
//port used
int port = 2040;
ServerSocket serverSocket = new ServerSocket(port);
System.out.println("Running on port " +port);
/*server always on
* creating a connection socket when contacted by client..
*/
while(true) {
//create connection socket when contacted
Socket client = serverSocket.accept();
//read input from client
BufferedReader input = new BufferedReader(new InputStreamReader(client.getInputStream()));
//whatever input or communication we want to have can operate in this string..
String x;
while((x = input.readLine()) != null){
System.out.println(x);
if(x.isEmpty()) {
break;
}
}
//output of client server..
OutputStream clientOutput = client.getOutputStream();
clientOutput.write("HTTP/1.1 200 OK\r\n".getBytes());
clientOutput.write("\r\n".getBytes());
clientOutput.write("".getBytes());
clientOutput.write("\r\n\r\n".getBytes());
Scanner fetch = new Scanner(new File("index.html"));
String myHTML_file = fetch.useDelimiter("\\Z").next();
fetch.close();
clientOutput.write(myHTML_file.getBytes("UTF-8"));
clientOutput.write("\r\n\r\n".getBytes());
clientOutput.flush();
System.out.println("Connection closed.");
clientOutput.close();
}
}
}
I'm working on a basic Client-Server connection.
This code works perfectly yet the client can only send 1 message and receive its modification before closing the connection.
how can I make it to send and receive multiple messages?
I thought of using a while loop yet I didn't know how to implement it correctly.
I need to be able to send more than 1 message in order to have a consistent connection
The code below is a client sending a string to the server and the server turns it to uppercase.
//Server:
public class TCPServer {
public static void main(String argv[]) throws Exception
{
String clientSentence;
String capitalizedSentence;
ServerSocket welcomeSocket = new ServerSocket(6789);
while(true)
{
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
clientSentence = inFromClient.readLine();
capitalizedSentence = clientSentence.toUpperCase() + '\n';
outToClient.writeBytes(capitalizedSentence);
if(clientSentence.toUpperCase().trim().contentEquals("QUIT")) {
connectionSocket.close();
}
}
}
}
//Client:
public class TCPClient {
public static void main(String argv[]) throws Exception
{
String sentence;
String modifiedSentence;
Socket clientSocket = new Socket("LocalHost", 6789);
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
System.out.print("Enter characters to be capitalized: ");
sentence = inFromUser.readLine();
outToServer.writeBytes(sentence + '\n');
modifiedSentence = inFromServer.readLine();
System.out.println("FROM SERVER: " + modifiedSentence);
}
}
the output for this code is:
Enter characters to be capitalized: hi
FROM SERVER: HI
Your Server can gets only one message from each client, because in your while-loop, in each iteration you call to welcomeSocket.accept(). This means that your server code stops until it gets new client connection.
Consider to use multi-threading if you want your server will support multiple clients. For example, take a look: on this post
I wanted to send/receive continuous stream of data from one endpoint to another(peer2peer) with push and pull 'able asynchronously
So to first solve communication , I started with jax-ws soap binding webservice since it has an endpoint and ws-addressing for push mechanism but it seems to be a lot of overhead (heavy as per the docs and since unfamiliar with ws-*, I haven't implemented it , as I need multiple clients listening to the stream at a later point and the stream is 24/7 I wanted thread manageable sockets).
Then I took jax-rs but it does not include ws-addressing in it.(jax-rs 2.0)
I also looked at websockets but it required an app server but I want a jvm supportable code
So, Now I am trying to use basic sockets but the problem I am having is streaming the data through socket at server and client receiving it continuously.
It is working for the first read but no further.
Secondly, how can I make it asynchronous?
public class sSocket {
public static void main(String args[]) throws IOException{
int i = 15000;
ServerSocket ss;
Socket socket = null;
ss = new ServerSocket(i);
try
{
socket = ss.accept();
socket.setKeepAlive(true);
int iii = 0;
System.out.println("New connection accepted " + socket.getInetAddress() + ":" + socket.getPort());
BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedWriter output = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
while(iii<9)
{
Thread.sleep(2000);
output.write("good" + iii + "\n");
//System.out.print(input.readLine().toString());
output.flush();
iii++;
}
//socket.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
public class cSocket {
public static void main(String args[]) throws InterruptedException, IOException{
Socket client = new Socket("127.0.0.1", 15000);
try{
client.setKeepAlive(true);
DataOutputStream out = new DataOutputStream(client.getOutputStream());
out.writeBytes("Hi Server! I'm " + client.getLocalSocketAddress() + "\n" );
BufferedReader input = new BufferedReader(new InputStreamReader(client.getInputStream()));
String s;
while(true){
if((s = input.readLine()) != null)
{
System.out.println("Message from Server: " + s);
}}
//client.close();
}
catch(Exception e){
e.printStackTrace();
}
}
}
[toString() unavailable - no suspended threads] I see this halting the code in eclipse.
The problem seems to be essentially rooted in the input.readLine() in client: error is connection reset : which I assume is because readLine() has reached "EOF"
Don't keep creating new streams. Use the same ones for the life of the socket, at both ends. You're losing data in the buffers.
You don't need to keep calling setKeepalive(). Once is enough.
I have coded a simple java client to send requests and receive data from my my java web server. The server is capable of handling persistent connections and everything works fine when I use browser to send requests however when I send requests using my client it only works with non persistent connections. when I use my java client to send requests it would receive the data requested from the server and then just freezes. My code for java client:
public static void main(String[] args) throws UnknownHostException, IOException {
// TODO code application logic here
String sentence;
String modifiedSentence;
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
Socket clientSocket = new Socket("127.0.0.1", 6789);
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
System.out.println("Enter the file name that you would like to request from Server:");
sentence = inFromUser.readLine();
System.out.println("would you like to have a persistent connection (yes/no):");
String sentence1 = inFromUser.readLine();
if(sentence1.equals("yes")){sentence1="Connection: keep-alive";}
else{sentence1="Connection: close";}
outToServer.writeBytes("GET /"+sentence + "\r\n");
outToServer.writeBytes(sentence1+"\r\n");
outToServer.writeBytes("\r\n");
while ((modifiedSentence=inFromServer.readLine()) != null)
{
System.out.println("FROM SERVER: " + modifiedSentence);
}
System.out.println("done");
clientSocket.close();
}
My guess is that you try to modifiedSentence=inFromServer.readLine() after the server closed the connection (which closes the socket and the other streams as well) and you get a java.net.SocketException.
Try surrounding it with try/catch and print the error message / stacktrace
I have to build a server and a client in Java. The server opens a connection on port 18163. The client connects to the server and establishes a number X, the server sends the message "guess", the server received the message repeatedly attempts to determine the value of X to the client sending the message "I feel Y" where Y is the value of a integer. When the client receives the message "I feel Y" sends to the server: "Same" if the number is correct, "Not equal if the number is not correct." If the number is correct, the server sends the client the "Close" and the client closes the connection.
I have to implement this program without the use of thread! I tried that, but it doesn't work.
CLIENT:
public class Client{
public static void main(String[] args)throws Exception{
Socket c= new Socket("127.0.0.1",18163);
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(c.getInputStream()));
DataOutputStream outToServer=new DataOutputStream(c.getOutputStream());
int min=1,max=10;
String frase;
int n1;
int numcasuale=(min+(int)(Math.random()*((max - min)+1)));
System.out.println("Num casuale generato: "+numcasuale);
do{
frase=inFromServer.readLine();
n1=Integer.parseInt(frase);
System.out.println("DAL SERVER: PROVO "+n1);
}while(!(n1==numcasuale));
outToServer.writeBytes("UGUALE\n");
frase=inFromServer.readLine();
if(frase.equals("CLOSE")){
System.out.println("Esecuzione terminata.");
c.close();
}
}
}
SERVER:
public class Server{
public static void main(String[] args)throws Exception{
ServerSocket ss = new ServerSocket(18163);
int min=1,max=10,numcasuale;
String dallclient;
while(true){
Socket c= ss.accept();
System.out.println("Client connesso: "+ c.getRemoteSocketAddress());
DataOutputStream alclient=new DataOutputStream(c.getOutputStream());
BufferedReader dalclient =new BufferedReader(new InputStreamReader(c.getInputStream()));
dallclient= dalclient.readLine();
System.out.println("DAL CLIENT :"+dallclient);
do{
numcasuale=(min+(int)(Math.random()*((max - min)+1)));
alclient.write(numcasuale);
dallclient= dalclient.readLine();
System.out.println("DAL CLIENT: "+dallclient);
}while(!(dallclient.equals("UGUALE")));
}alclient.writeBytes("CLOSE\n");
}
}
I think in the server part you are missing an \n at this line:
while( !(dallclient.equals("UGUALE")) );
since the client is sending "UGUALE\n"
outToServer.writeBytes("UGUALE\n");