Java TCP client/server sockets - java

I am working on a problem that will create a TCP server and client using sockets. For the client code, my objective is to repeatedly prompt the user to enter a sentence S, send the sentence S to the server, receive the response from the server, and display the message received and the round trip time expressed in milliseconds. On the server, my objective is to create a TCP server socket, wait for a client to connect, receive a message, display it with the IP address and port # of the client, capitalize the message, display the message, and echo back the "capitalized" message.
I am trying to use a while (!(input.equals("done"){ ...do something }, however, whatever I do is getting stuck in an infinite loop. I hope its something simple I am just overlooking, but I don't see it.
TCPServer.java
import java.net.*;
import java.io.*;
public class myFirstTCPServer {
public static void main(String[] args) throws IOException {
int servPort = 4999;
ServerSocket Sy = new ServerSocket(servPort);
Socket servSocket = Sy.accept();
InputStreamReader in = new InputStreamReader(servSocket.getInputStream());
BufferedReader bf = new BufferedReader(in);
String str = bf.readLine();
while (!(str.equals("done"))){
System.out.println("client connected");
InetAddress address = InetAddress.getLocalHost();
String ip = address.getHostAddress();
System.out.println("IP: " + ip);
System.out.println("Port: " + servPort);
System.out.println("Message from client: " + str.toUpperCase());
PrintWriter pr = new PrintWriter(servSocket.getOutputStream());
pr.println(str);
pr.flush();
}
servSocket.close();
}
}
TCPClient.java
import java.net.*;
import java.io.*;
import java.util.Scanner;
public class myFirstTCPClient {
public static void main(String[] args) throws IOException {
String S;
Scanner input = new Scanner(System.in);
System.out.println("Enter a sentence");
S = input.nextLine();
Socket clntSocket = new Socket(InetAddress.getLocalHost(), 4999);
while (!(S.equals("done"))){
double sent = System.nanoTime();
PrintWriter pr = new PrintWriter(clntSocket.getOutputStream());
pr.println(S);
pr.flush();
InputStreamReader in = new InputStreamReader(clntSocket.getInputStream());
BufferedReader bf = new BufferedReader(in);
String str = bf.readLine();
System.out.println("Message from server: " + str);
double received = System.nanoTime();
double total = received - sent;
System.out.println("Round Trip Time: " + (total/1000000.0));
}
clntSocket.close();
}
}

you need to move reader into the while loop. Because this is where server waits for reading clients input.
public class myFirstTCPServer {
public static void main(String[] args) throws IOException {
int servPort = 4999;
ServerSocket Sy = new ServerSocket(servPort);
Socket servSocket = Sy.accept();
System.out.println("client connected");
InputStreamReader in = new InputStreamReader(servSocket.getInputStream());
BufferedReader bf = new BufferedReader(in);
String str ="";
while (true)){
str = bf.readLine();
if(str.equals("done")) break;
InetAddress address = servSocket.getInetAddress();
String ip = address.getHostAddress();
System.out.println("IP: " + ip);
System.out.println("Port: " + servPort);
System.out.println("Message from client: " + str);
PrintWriter pr = new PrintWriter(servSocket.getOutputStream());
pr.println(str.toUpperCase());
pr.flush();
}
servSocket.close();
}
}
And then change client side:
public class myFirstTCPClient {
public static void main(String[] args) throws IOException {
String S="";
Scanner input = new Scanner(System.in);
// you need to provide your server ip/domain
// InetAddress.getLocalHost() , still works but only works when
// your client is in the same machine.
Socket clntSocket = new Socket("127.0.0.1", 4999);
while (!(S.equals("done"))){
System.out.println("Enter a sentence");
S = input.nextLine();
double sent = System.nanoTime();
PrintWriter pr = new PrintWriter(clntSocket.getOutputStream());
pr.println(S);
pr.flush();
InputStreamReader in = new InputStreamReader(clntSocket.getInputStream());
BufferedReader bf = new BufferedReader(in);
String str = bf.readLine();
System.out.println("Message from server: " + str);
double received = System.nanoTime();
double total = received - sent;
System.out.println("Round Trip Time: " + (total/1000000.0));
}
clntSocket.close();
}
}

Related

Why is my program running twice on my Server?

I am writing tcp client-server program. When the client types "Hello" the server returns a list of files and directories of his current directory. When the client types "FileDownload " it downloads the selected file from the server.
When I type "Hello" it works fine, but when I type "FileDownload ", on the server side it runs twice the else if(received.contains("FileDownload")) block. Because of this the server is sending twice the data which is causing other issues on the client side.
Here is the server code:
public static void main(String[] args) throws IOException {
ServerSocket servSock = new ServerSocket(1333);
String received="";
String[] s = null;
File[] f1;
int i=0;
File f=new File(System.getProperty("user.dir"));
f1=f.listFiles();
for(File f2:f1) {
if(f2.isDirectory())
System.out.println(f2.getName() + "\t<DIR>\t" + i);
if(f2.isFile())
System.out.println(f2.getName() + "\t<FILE>\t" + i);
i++;
}
while (true) {
Socket client = servSock.accept();
InputStream in = client.getInputStream();
OutputStream out = client.getOutputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
PrintWriter pw = new PrintWriter(out, true);
s=f.list();
while(true) {
received = reader.readLine();
if(received.equals("END")) break;
if(received.equals("Hello")) {
System.out.println("Hello-Start");
int length=f1.length;
pw.println(length);
i=0;
for(File f2:f1) {
if(f2.isDirectory())
pw.println(f2.getName() + "\t<DIR>\t" + i);
if(f2.isFile())
pw.println(f2.getName() + "\t<FILE>\t" + i);
i++;
}
pw.println("Options: " + "\tFileDownload <FID>" + "\tFileUpload <name>" + "\tChangeFolder <name>");
System.out.println("Hello-End");
}
else if(received.contains("FileDownload")) {
System.out.println("FileDownload-Start");
int j=-1;
try {
j=Integer.parseInt(received.substring(13).trim());
}catch(NumberFormatException e) {
System.err.println("error: " + e);
}
if(j>0 && j<s.length) {
FileInputStream fi=new FileInputStream(s[j]);
byte[] b=new byte[1024];
System.out.println("file: "+s[j]);
pw.println(s[j]);
fi.read(b,0,b.length);
out.write(b,0,b.length);
System.out.println("FileDownload-End");
}
}
Here is the client code:
public static void main(String[] args) throws IOException {
if ((args.length != 2))
throw new IllegalArgumentException("Parameter(s): <Server> <Port>");
Socket socket = new Socket(args[0], Integer.parseInt(args[1]));
Scanner sc = new Scanner(System.in);
InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
PrintWriter pw = new PrintWriter(out, true);
while(true) {
String msg="", received="";
String length;
msg = sc.nextLine();
pw.println(msg);
if(msg.equals("END")) break;
if(poraka.equals("Hello")) {
System.out.println();
length = reader.readLine();
for(int i=0;i<Integer.parseInt(length);i++) {
received = reader.readLine();
System.out.println(received);
}
System.out.println("\n"+reader.readLine());
}
else if(msg.contains("FileDownload")) {
System.out.println("FileDownload-Start");
pw.println(msg);
byte[] b=new byte[1024];
File file=new File(reader.readLine().trim());
System.out.println(file.getName().trim());
FileOutputStream fo=new FileOutputStream("D:\\Eclipse WorkSpace\\proekt\\src\\client\\"+file.getName().trim());
System.out.println("file: "+file.getName().trim());
in.read(b,0,b.length);
fo.write(b,0,b.length);
System.out.println("FileDownload-End");
}
I could not find what's causing this issue, so any help possible would be very highly appreciated!
It is because your client requests the data twice:
msg = sc.nextLine();
pw.println(msg); // <-- this is the first time
and then later
else if(msg.contains("FileDownload")) {
System.out.println("FileDownload-Start");
pw.println(msg); // <-- this is the second time

Why server created using java socket doesn't not print data send from client (it dislays if client terminate)?

In example below I created one server which will only print whatever client is writing in a socket. But I am not getting output as client enter data. If client terminate then I can see all the data client inserted in outputstream. I am taking input from console at client and then write that data to server socket.
Server code:
public class server {
public static void main(String[] args) throws Exception {
System.out.println("waiting");
ServerSocket s = new ServerSocket(9999);
Socket stemp = s.accept();
System.out.println("read comp");
InputStream is = stemp.getInputStream();
InputStreamReader ir = new InputStreamReader(is);
BufferedReader br = new BufferedReader(ir);
while(true)
{
String str = br.readLine();
if(str!=null)
{
System.out.println(str);
}
if(str.contains("exit"))
{
break;
}
}
stemp.close();
ir.close();
is.close();
br.close();
}
}
Client code:
public class client {
public static void main(String[] args) throws Exception {
String ip ="127.0.0.1";
int port = 9999;
Socket s1 = new Socket(ip, port);
OutputStream os = s1.getOutputStream();
OutputStreamWriter ow = new OutputStreamWriter(os);
BufferedWriter pw = new BufferedWriter(ow);
pw.write("I am ready");
Scanner s = new Scanner(System.in);
String str = s.nextLine();
System.out.println(str);
while(!str.contains("exit"))
{
pw.write(str);
pw.flush();
str = s.nextLine();
}
pw.close();
os.close();
ow.close();
s1.close();
}
}
In server, br.readLine(); is used, waiting for end-of-line.
In client, you have to send the eol in pw.write( str + '\n' );.

print multiple lines using sockets in java

I'm creating a simple client-server to use with my Raspberry Pi.
What I'm trying to accomplish is to send "ACKTEMP" for example to the Server using my Client. The servers then calls the serial port (which is my STM32 Nucleo Board btw) with this message I get the temperature back using the serial communication and after that it sends it back to the Client.
My question is, the Nucleo board returns some strings like (TEMP: xx) this works fine until I start sending multiple strings back at once ex. if I send ACKTEMP and want to receive (TEMP: xx ) and "Temperature OK", doing this I only get the first line which is (TEMP: xx ).
So it seems that somewhere in my code I need to change something so it prints out all the lines instead of just one and then stop. Please don't get angry at me if my programming isn't that great I'm a student and trying to understand everything.
public class Client {
/**
* #param args the command line arguments
* #throws java.io.IOException
*/
public static void main(String[] args) throws IOException {
String sentence;
String messageFromServer;
while(true)
{
BufferedReader inFromUser = new BufferedReader( new InputStreamReader(System.in));
try (Socket clientSocket = new Socket("192.168.0.135", 6789)) {
PrintWriter outToServer = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
sentence = inFromUser.readLine();
outToServer.println(sentence + '\n');
messageFromServer = inFromServer.readLine();
System.out.println("FROM SERVER: " + messageFromServer);
clientSocket.close();
}
}
}
}
public class Server {
private static SerialPort serialPort;
/**
* #param args the command line arguments
* #throws java.io.IOException
*/
public static void main(String[] args) throws IOException {
String clientSentence;
String capitalizedSentence;
ServerSocket welcomeSocket = new ServerSocket(6789);
serialPort = new SerialPort("/dev/ttyACM0");
while(true)
{
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
PrintWriter outToClient = new PrintWriter(connectionSocket.getOutputStream(), true);
clientSentence = inFromClient.readLine();
try{
//opening port
serialPort.openPort();
serialPort.setParams(
SerialPort.BAUDRATE_115200,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
//Write string to port
serialPort.writeString(clientSentence + "\n");
System.out.println("String wrote to port, waiting for response..");
try {
Thread.sleep(10); //1000 milliseconds is one second.
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
String buffer = serialPort.readString();
outToClient.println(buffer + '\n');
serialPort.closePort();//Close serial port
}
catch(SerialPortException ex){
System.out.println("Error writing data to port: " + ex);
}
}
// TODO code application logic here
}
}
I used the following to kinda solve this problem. But if someone has a better solution it is very welcome!
What I did is for every string I want a new line, I put a "~" sign in front of the string in my Nucleo STM32 program.
String strArray[] = messageFromServer.split("~");
System.out.println("FROM SERVER: " + strArray[0]);
for(int i = 1; i < strArray.length; ++i)
{
if(messageFromServer.indexOf('~') >= 0)
{
System.out.println("FROM SERVER: " + strArray[i]);
}
}

Filtering URL content in a self written proxy using Java

I need to code some proxy server for an assignment in my university. It should be able to display the content of some simple web page given by our professor.
Additionally it should filter the URL and the URL content, and block the web page if one of these contain one of the words in my "bad" array.
My question is, how can I perform this filtering in Java.
Code:
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class ProxyServer{
//Crate the Port the user wants the proxy to be on
static Scanner sc = new Scanner(System.in);
public static final int portNumber = sc.nextInt();
public static void main(String[] args) {
ProxyServer proxyServer = new ProxyServer();
proxyServer.start();
}
public void start() {
System.out.println("Starting the SimpleProxyServer ...");
try {
String bad[]= new String[4];
bad[0]= "Spongebob";
bad[1]= "Britney Spears";
bad[2]= "Norrköping";
bad[3]= "Paris Hilton";
ServerSocket serverSocket = new ServerSocket(ProxyServer.portNumber);
System.out.println(serverSocket);
byte[] buffer= new byte [1000000] ;
while (true) {
Socket clientSocket = serverSocket.accept();
InputStream inputstream = clientSocket.getInputStream();
System.out.println(" DAS PASSIERT VOR DEM BROWSER REQUEST:");
int n = inputstream.read(buffer);
String browserRequest = new String(buffer,0,n);
System.out.println("Das ist der Browserrequest: "+browserRequest);
System.out.println("Das ist der Erste Abschnitt");
int start = browserRequest.indexOf("Host: ") + 6;
int end = browserRequest.indexOf('\n', start);
String host = browserRequest.substring(start, end - 1);
System.out.println("Connecting to host " + host);
Socket hostSocket = new Socket(host, 80); //I can change the host over here
OutputStream HostOutputStream = hostSocket.getOutputStream();
PrintWriter writer= new PrintWriter (HostOutputStream);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputstream));
String Input= null;
while (((Input= reader.readLine())!= null)){
writer.write(Input);
writer.flush();
System.out.println("Empfangen vom Client: "+Input);
}
// for (int i=0; i<4;i++){
// if (inString.contains(bad[i])){
// System.out.println("Bye Idiot");
// break;
// }
// }
System.out.println("Forwarding request to server");
HostOutputStream.write(buffer, 0, n);// but then the buffer that is fetched from the client remains same
HostOutputStream.flush();
InputStream HostInputstream = hostSocket.getInputStream();
OutputStream ClientGetOutput = clientSocket.getOutputStream();
System.out.println("Forwarding request from server");
do {
n = HostInputstream.read(buffer);
String inhalt= HostInputstream.toString();
System.out.println("das ist der inhalt vom HOST: "+ inhalt);
String vomHost = new String(buffer,0,n);
System.out.println("Vom Host\n\n"+vomHost);
// for(int i=0;i<n;i++){
// System.out.print(buffer[i]);
// }
System.out.println("Receiving " + n + " bytes");
if (n > 0) {
ClientGetOutput.write(buffer, 0, n);
}
} while (HostInputstream.read(buffer)!= -1);//n>0
ClientGetOutput.flush();
hostSocket.close();
clientSocket.close();
System.out.println("End of communication");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

a client/server program using java won't work

I'm trying to create a client/server program with java.
when the client connect to the server, the server will show him a message to enter the first value when the user write the first value the server sends him a message to write the sencd value when the user write the second value the server will show him a list of operations ans wait until the client write the number of the operation and then the server will send him the result of this operation.
When I write the program's code and run the server and then the client, it doesn't do any thing the server is blocked from doing anything, also the client.
this is the code I tried :
for the client :
import java.net.*;
import java.util.Scanner;
import java.io.*;
public class Client {
final static String ADRSS = "localhost";
final static int PORT = 1234;
static Socket s = null;
public static void main(String[] args) {
try{
Scanner cn = new Scanner(System.in);
s = new Socket(ADRSS, PORT);
PrintWriter out = new PrintWriter(s.getOutputStream());
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
in.readLine();
out.println(cn.nextLine());
out.flush();
in.readLine();
out.println(cn.nextLine());
out.flush();
in.readLine();
out.println(cn.nextLine());
out.flush();
System.out.println("Res = " + in.readLine());
out.flush();
}
catch(IOException e){e.printStackTrace();
}
}
}
for the server:
import java.net.*;
import java.io.*;
public class Server {
final static int PORT = 1234;
private static ServerSocket server;
public static void main(String[] args) {
Socket s = null;
try {
server = new ServerSocket(PORT);
s = server.accept();
PrintWriter out = new PrintWriter(s.getOutputStream());
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
out.println("Donner le premier nombre : ");
out.flush();
double n1 = Double.parseDouble(in.readLine());
out.println("Donner le deuxiéme nombre : ");
out.flush();
double n2 = Double.parseDouble(in.readLine());
out.println("Donner l'op : ");
out.flush();
String choix = in.readLine();
String res = null;
switch(choix){
case "1" :
res = String.valueOf(n1 + n2);
break;
case "2" :
res = String.valueOf(n1 - n2);
break;
case "3" :
res = String.valueOf(n1 * n2);
break;
case "4" :
res = (n2 == 0) ? "Impossible d'éfectuer l'op" : String.valueOf(n1 / n2);
break;
default :
res = "erreur";
}
out.println(res);
out.flush();
}catch(IOException e) {
e.printStackTrace();
}finally{
try{
s.close();
}catch(IOException e){e.printStackTrace();}
}
}
}
PrintWriter doesn't flush output after you use regular print (refer to documentation of PrintWriter). You'd have to flush it manually. However, the real reason is your client waits for a line with newline, which never happens. Changing to out.println on the server side should make this running, also covering the flushes.
first, after every print in the server, add
out.flush();
second, you are asking for nextLine() but printing without \n ,
either add \n to end of each string or use out.println

Categories

Resources