I’m following an example from java net programing, and decided to write a client-server in java-scala respectively, here’s the scala code:
import scala.actors.Actor
import scala.actors.Actor._
import java.io._
import java.net._
class EchoActor(private val sock: Socket,
private val id: Int) extends Actor{
def act(){
try{
val in = new BufferedReader(
new InputStreamReader(sock.getInputStream()))
val out = new PrintWriter(
sock.getOutputStream(), true)
out.println("Hello! press BYE to exit")
var done = false
while(!done){
var str = in.readLine()
if (str == null) done = true
else{
println(str) // debug
out.println("Echo (" + id + "): " + str)
if (str.trim().equals("BYE")) done = true
}
}
sock.close()
}
catch{
case e => e printStackTrace
}
}
}
object Main{
def main(args: Array[String]){
try{
var i = 1
val s = new ServerSocket(8189)
while(true){
var inc = s.accept()
println("Spawning " + i)
var a = new EchoActor(inc, i)
a.start()
i += 1
}
}
catch{
case e => e printStackTrace
}
}
}
And here’s java’s:
import java.net.*;
import java.io.*;
public class Client{
public static void main(String[] args){
try{
Socket s = new Socket("127.0.0.1",8189);
BufferedReader in = new BufferedReader(
new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(
s.getOutputStream(), true);
BufferedReader socketIn = new BufferedReader(
new InputStreamReader(s.getInputStream()));
System.out.println("Enter: to exit");
String resp;
String st
while(true){
st = in.readLine();
if(st.equals("exit") || st.equals("quit")) break;
else{
out.println(st);
resp = socketIn.readLine();
System.out.println(resp);
}
}
}
catch(Exception e){
e.printStackTrace();
}
}
}
The output from the server:
Spawning 1
s
s
l
l
scala
java
java’s output:
Enter: to exit
s
Hello! press BYE to exit
Echo (1): s
s
Echo (1):
Echo (1): s
l
Echo (1):
l
Echo (1): l
scala
Echo (1): l
Echo (1): scala
java
Echo (1):
Echo (1): java
As you can see im receiving Echo (1) response empty where i expect to print the Echo (1) plus the string i just send, you got to re-type “Enter” to get the string previouly send, so that’s the problem, i need just one response from the server like this just once: Echo (1): some string, i’m out of ideas, i tracked it with printing to the console but can’t figure out what’s going on.
Edit:
Expected client’s output:
...
s
Echo (1): s
java
Echo (1): java
On the expected output you don’t have to re-type enter to get the response from the server.
Server’s output is already working as expected.
You are getting confused because you are sending “Hello! press BYE to exit” when the client first connects, but the client doesn’t actually read this line specifically. So you are reading it in the client when you are expecting to read the echoed message you sent, so your client is always reading one echo behind where you think it is up to.
Solution: either remove the “Hello! press BYE to exit” from the server, or read it when you first connect the client, before you enter the loop.