Java communication via sockets - java

I'm trying to implement basic TCP communication via sockets and the problem is that it doesn't work. When I enter few sentences from client, the server receives only the first sentence and reply it back.
Client :
String sentence;
String modifiedSentence;
BufferedReader inFromUser = new BufferedReader( new InputStreamReader(System.in));
Socket clientSocket = new Socket("localhost", 5055);
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
while(!(sentence = inFromUser.readLine()).equals("end")) {
outToServer.writeBytes(sentence + '\n');
modifiedSentence = inFromServer.readLine();
System.out.println("FROM SERVER: " + modifiedSentence);
}
clientSocket.close();
Server:
String clientSentence;
String capitalizedSentence;
ServerSocket welcomeSocket = new ServerSocket(5055);
while (true) {
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient =
new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
clientSentence = inFromClient.readLine();
System.out.println("Received: " + clientSentence);
capitalizedSentence = clientSentence.toUpperCase() + '\n';
outToClient.writeBytes(capitalizedSentence);
}

Related

How to read data until eof() using BufferdReader in java

Hi I'm facing a little problem with eof()
I created a tcp connection between a client and a server to send text to the server and
receive it back in capital letters but the problem is that it's reading one line only so
I would like to modify the code so it reads until I type "stopp". When I type stop both
the client and the receiver terminate at the same time.
This is the client class
import java.io.*;
import java.net.*;
public class Klient {
/**
* #param args
* #throws IOException
* #throws UnknownHostException
*/
public static void main(String[] args) throws UnknownHostException,
IOException {
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()));
while (true){
sentence = inFromUser.readLine();
outToServer.writeBytes(sentence + '\n');
modifiedSentence = inFromServer.readLine();
System.out.println(modifiedSentence);
}
//clientSocket.close();
}
}
This is the server class
import java.io.*;
import java.net.*;
public class TCPServer {
/**
* #param args
* #throws IOException
*/
public static void main(String[] args) throws IOException {
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);
}
}
It is only reading one sentence because the server does not repeatedly ask for new input. Sure, you have a while(true) loop, but that loop is repeatedly accepting new connections (this is what welcomeSocket.accept() does). Once you asked for one line input, you go back to the start of the loop, and waits for another connection to come. Of course, no more connections are coming, so the server just does nothing forever.
You should add an inner loop,
while (true){
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
while(true) {
clientSentence = inFromClient.readLine();
if (clientSentence.equalsIgnoreCase("stop")) {
connectionSocket.close();
break;
}
capitalizedSentence = clientSentence.toUpperCase() + '\n';
outToClient.writeBytes(capitalizedSentence);
}
}
Once the server receives "stop", it would close the connection with the current client, and wait for another client to connect as it goes back to the top of the outer loop. If you want the server to terminate completely (so only accepting one connection), just remove the outer loop, and close the welcomeSocket:
ServerSocket welcomeSocket = new ServerSocket(6789);
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
while(true) {
clientSentence = inFromClient.readLine();
if (clientSentence.equalsIgnoreCase("stop")) {
connectionSocket.close();
break;
}
capitalizedSentence = clientSentence.toUpperCase() + '\n';
outToClient.writeBytes(capitalizedSentence);
}
welcomeSocket.close();
As for the client, it can break out of the loop when inFromServer.readLine returns null, which is indication that the connection has been closed.
while (true){
sentence = inFromUser.readLine();
outToServer.writeBytes(sentence + '\n');
modifiedSentence = inFromServer.readLine();
if (modifiedSentence == null) {
break;
}
System.out.println(modifiedSentence);
}

Send an object from a client to a server in java

How do i send an object to a server in java?
Client:
Help h = new Help("Mattia Cammalleri","Informatica","18 Novembre 2020");
Socket s = new Socket("localhost", 8888);
ObjectOutputStream os = new ObjectOutputStream(s.getOutputStream());
ObjectInputStream is = new ObjectInputStream(s.getInputStream());
os.writeObject(h);
os.flush();
Server:
ServerSocket ss = new ServerSocket(8888);
Socket s = ss.accept();
ObjectOutputStream os = new ObjectOutputStream(s.getOutputStream());
ObjectInputStream is = new ObjectInputStream(s.getInputStream());
Help h = (Help) is.readObject();
System.out.println("Richiesta " + h);
Object (implements serializable):
public String alunno;
public String materia;
public String data;
Why it doesn't work?
I solved it in this way:
Client:
Help h = new Help("Mattia Cammalleri","Informatica","18 Novembre 2020");
Socket socket = new Socket("localhost", 7777);
System.out.println("Connected");
OutputStream outputStream = socket.getOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
System.out.println("The object has been sent");
objectOutputStream.writeObject(h);
socket.close();
Server:
ServerSocket ss = new ServerSocket(7777);
System.out.println("Waiting for the client");
Socket socket = ss.accept();
System.out.println("Connected from " + socket + "!");
InputStream inputStream = socket.getInputStream();
ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
Help h = (Help) objectInputStream.readObject();
System.out.println("Object: " + h);
ss.close();
socket.close();

Java Client/Server error: Connection reset

Hello i have a client server program and the server side works while the client side is having some problems. The client prints out a message once it connects, but after some user input (which is not used yet) i get this error. The server prints out a text file with line numbers and sequence numbers(seq nums aren't quite right yet) and is supposed to send the line numbers, seq numbers and lines of text to the client.
Server:
public class STSServer {
/**
* #param args the command line arguments
*/
public static void main(String argv[]) throws Exception
{
String startLineFromClient;
String endLineFromClient;
String stringLineNumber;
String stringSeqNumber;
String test = "hello";
int convertStart;
int convertEnd;
int subtractStartEnd;
int temp;
int byteTransfer;
int lineNumber = 0;
int sequenceNumber;
ServerSocket welcomeSocket = new ServerSocket(6789);
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient =
new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient =
new DataOutputStream(connectionSocket.getOutputStream());
try{
File myFile = new File("alice.txt");
FileReader fileReader = new FileReader(myFile);
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuffer stringBuffer = new StringBuffer();
String line;
startLineFromClient = inFromClient.readLine();
endLineFromClient = inFromClient.readLine();
convertStart = Integer.parseInt(startLineFromClient);
convertEnd = Integer.parseInt(endLineFromClient);
while((line = bufferedReader.readLine()) != null)
{
sequenceNumber = line.length();
System.out.print(lineNumber);
stringLineNumber = Integer.toString(lineNumber);
outToClient.writeBytes(stringLineNumber);
System.out.print(" ");
System.out.print(sequenceNumber);
stringSeqNumber = Integer.toString(sequenceNumber);
outToClient.writeBytes(stringSeqNumber);
System.out.print(" ");
System.out.print(line);
outToClient.writeBytes(line);
System.out.println("");
lineNumber++;
//stringLineNumber = Integer.toString(lineNumber);
//stringSeqNumber = Integer.toString(sequenceNumber);*/
// outToClient.writeBytes(test);
}
fileReader.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
Client:
public class STSClient {
public static void main(String argv[])throws Exception
{
String startLine;
String endLine;
String lineNumber;
String seqNumber;
String line;
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
Socket clientSocket = new Socket("localhost", 6789);
DataOutputStream outToServer =
new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer =
new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
while (true)
{
System.out.println("+++++++++++++++++++++++++++++++++++++++++++++");
System.out.println("+++++++++++++++ Simple TCP Service (STS)+++++");
System.out.println("+++++++++++++++++++++++++++++++++++++++++++++");
System.out.println("Command allowed by the server for this client:");
System.out.println("download [starting line #] [ending line #]");
System.out.print("Command: ");
startLine = inFromUser.readLine();
endLine = inFromUser.readLine();
outToServer.writeBytes(startLine + '\n');
outToServer.writeBytes(endLine + '\n');
lineNumber = inFromServer.readLine();
seqNumber = inFromServer.readLine();
line = inFromServer.readLine();
System.out.print(lineNumber);
System.out.print(seqNumber);
System.out.print(line);
System.out.println("");
}
}
}
Error:
Exception in thread "main" java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(SocketInputStream.java:209)
at java.net.SocketInputStream.read(SocketInputStream.java:141)
at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:284)
at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:326)
at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:178)
at java.io.InputStreamReader.read(InputStreamReader.java:184)
at java.io.BufferedReader.fill(BufferedReader.java:161)
at java.io.BufferedReader.readLine(BufferedReader.java:324)
at java.io.BufferedReader.readLine(BufferedReader.java:389)
at stsclient.STSClient.main(STSClient.java:42)
Your client is reading lines.
Your server is not sending lines.
Your server exits without closing the socket, which resets it on Windows.
Your client is still stuck in the first readLine() waiting for a line terminator.
It gets a connection reset instead.
Solution: send lines, and don't exit without closing the socket.

Java Client Server

I am trying to pass message from server to client in terminal. What I would like the program to do is, in the client, it should be able to enter a command, get response from server, and be able to enter another command without restarting Client (by java Client).
Client.java
Socket socket = new Socket(host, port);
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String response = "";
boolean continuation = true;
while(continuation) {
Scanner input = new Scanner(System.in);
String command = (input.nextLine()).toString();
bw.write(command+"\r\n");
bw.flush();
if(command.equals("cmd1") {
while ((response = br.readLine()) != null) {
System.out.println(response);
}
}
System.out.println("This line will not execute as well.");
}
Server.java
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
String[] in = br.readLine().split("\\s+");
String command = in[0];
if(command.equals("cmd1")) {
String response = "";
response = response + "RESPONSE:\r\n";
response = response + "This is a response.\r\n";
bw.write(response);
bw.flush();
}
If I don't put while((response = br.readLine()!= null) { ... } in Client.java, it is possible to enter multiple inputs in the terminal, but if I put it, it prints the response from the server and another input cannot be done without restarting Client.
Any help would be appreciated.
Thanks
This should work:
server:
DataInputStream dis = new DataInputStream(socket.getInputStream());
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
boolean continuation = true;
while (continuation) {
String command = dis.readUTF();
//proceeed command
dos.writeUTF("response");
dos.flush();
}
Client:
DataInputStream dis = new DataInputStream(socket.getInputStream());
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
dos.writeUTF("your command");
while (dis.available() == 0) {
try {
//wait for response
Thread.sleep(1);
} catch (InterruptedException ex) {
Logger.getLogger(RandomTest.class.getName()).log(Level.SEVERE, null, ex);
}
}
String response = dis.readUTF();
//and so on

Java Multithreaded Server Client Application

I need to make these code's multithreaded. I searched everywhere but i cant figure it out. Can you guys do it for me ?
Client.java's main method
Socket clientSocket = null;
PrintWriter out = null;
BufferedReader in = null;
String senddata;
try{
clientSocket = new Socket("localhost",5555);
}catch(IOException e){
System.out.println("Connection Error!");
}
out = new PrintWriter(clientSocket.getOutputStream(),true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
System.out.print("------------------------------------------------------------\nEnter The Data That Will Send The Server = ");
BufferedReader data = new BufferedReader(new InputStreamReader(System.in));
while(!(senddata = data.readLine()).equals("STOP")){
out.println(senddata);
System.out.println("Response The Client = " + in.readLine());
System.out.print("------------------------------------------------------------\nEnter The Data That Will Send The Server = ");
}
out.close();
in.close();
data.close();
clientSocket.close();
Server.java's main method
ServerSocket serverSocket = null;
Socket clientSocket = null;
String receivedData;
try{
serverSocket = new ServerSocket(5555);
}catch(IOException e){
System.out.println("Port Error!");
}
clientSocket = serverSocket.accept(); // Bağlantıyı Sağlayan Kod Satırı. Bağlantı Sağlanmadan Bir Alt Satıra Geçilmez.
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(),true); // Clienta Veri Gönderimi İçin PrintWriter Nesnesi Oluşturuldu!
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); // Clientden Gelen Verileri Tutan BufferedReader Nesnesi Oluşturuldu!
while(!(receivedData = in.readLine()).equals("STOP")){
System.out.println("------------------------------------------------------------\nReceived Data From Client = " + receivedData);
System.out.println("Response = " + receivedData);
out.println(receivedData);
}
out.close();
in.close();
serverSocket.close();
clientSocket.close();

Categories