Socket java client-server - java

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");

Related

Whenever I run my server on the specified port, it returns illegible characters. Why?

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();
}
}
}

TCP Server and Client in Java

I tried building a TCP server and client using Java. They can connect, they work well, but I have a single error.
This is the server side:
package com.company;
import java.io.*;
import java.net.*;
public class Main {
public static void main (String[] args) throws IOException {
System.out.println("The server is ready");
ServerSocket serverSocket = new ServerSocket (1234);
Socket clientSocket = serverSocket.accept ();
BufferedReader in = new BufferedReader (new InputStreamReader (clientSocket.getInputStream ()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
String message, modifiedMessage;
message = in.readLine ();
System.out.print("The received message from client: " + message);
modifiedMessage = message.toUpperCase();
out.print(modifiedMessage);
System.out.println ("\nModified message which is sent to client: " + modifiedMessage);
}
}
The server will have to receive a message from a client, then transforming it in an upper case string.
The client side is:
package com.company;
import java.io.*;
import java.net.*;
public class Main {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("127.0.0.1", 1234);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
System.out.println("Enter a lowercase sentence: ");
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
BufferedReader in = new BufferedReader((new InputStreamReader(socket.getInputStream())));
String messageSent = reader.readLine();
System.out.println("The message sent is: " + messageSent);
out.println(messageSent);
String messageReceived = in.readLine();
System.out.println("The modified message is: " + messageReceived);
}
}
I want the client to be able to print both the lower case sentence and the received (modified) upper case sentence. The problem is that, when I enter a simple word, say hello, my client will only print the original string, not the modified one.
The output of the server is:
The received message from client: hello
The modified message sent to the client is: HELLO
But the output of the client is:
The message sent is: hello
The modified message is: null
I know that the server is able to convert the string to the upper-case version and to connect to my client. Why doesn't my client print the received message? Doesn't it actually receive it?
You need to flush the message. PrintWriter calls flush in println, print doesn't.
on the server side you need to change to:
out.println(modifiedMessage);
instead of
out.print(modifiedMessage);

Simple Java Networking Program

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

client requesting from web server

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

client acting both a as a client and server - JAVA

I have an interesting question. I am trying to establish a peer to peer connection which means a client process acts both as a server and client. Ideally, it should have a client socket (Socket class) and a server socket(Server Socket class). Now I tried to use this concept but it does not work. Please take a look at it:
public static void main(String argv[]) throws Exception
{
Socket clientSocket = null;
BufferedReader inFromUser = new BufferedReader( new InputStreamReader(System.in));
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
System.out.println("Enter the server port u want to be assigned to this peer:");
sentence = inFromUser.readLine();
System.out.println("writing current port to client = "+ sentence);
outToServer.writeBytes("p~"+sentence + "\n" );
int serverport = Integer.parseInt(sentence);
ServerSocket server = new ServerSocket(serverport);
Socket client;
//client
System.out.println("enter port no of the server port of an other peer:");
int msg=Integer.parseInt(inFromUser.readLine());
clientSocket = new Socket("localhost", msg);
outToServer = new DataOutputStream(clientSocket.getOutputStream());
outToServer.writeBytes("hi");
while(true)
{
//server port listens infinitely and spawns new thread
System.out.println("inside true");
client = server.accept();
Thread serverThread = new Thread(new acceptconnection1(client));
serverThread.start();
}}}
class acceptconnection1 implements Runnable {
BufferedReader inFromClient, inn;
DataOutputStream ds;
Socket socket;
int peersocket;
String clientSentence;
int serverport ;
Socket clientSocket = null;
acceptconnection1 (Socket socket,) throws IOException{
this.socket = socket;
inn = new BufferedReader (new InputStreamReader(System.in));
inFromClient =new BufferedReader(new InputStreamReader(socket.getInputStream()));
ds = new DataOutputStream(socket.getOutputStream());
}
#Override
public void run () {
String cs,a;
try {
System.out.println("waiting for connection ");
if(( clientSentence = inFromClient.readLine())!=null)
{
System.out.println("Message from other peer" + clientSentence);
}
} catch (IOException ex) {
Logger.getLogger(acceptconnection1.class.getName()).log(Level.SEVERE, null, ex);
}}}
Output:
when I create two client processes,
o/p of client1:
Enter the server port u want to be assigned to this peer:
1111
writing current port to client = 1111
hi enter port no u want to connect to:
2222
inside true
inside true
waiting for connection
Enter the server port u want to be assigned to this peer:
2222
writing current port to client = 2222
hi enter port no u want to connect to:
1111
inside true
inside true
waiting for connection
what happens is both of them wait for connections. how do i solve this?
You have a deadlock condition. To result this, create the ServerSocket first so the Socket has something to talk to. Create the Socket which will connect but do nothing until accepted. Then accept connections.
BTW: You don't need to create two connections for traffic to pass both ways. Once a connection has been established, you can use that one connection as client-server, or server-server or what ever.

Categories