我正在关注 java net 编程中的一个示例,并决定分别在 java-scala 中编写一个客户端-服务器,这是 scala 代码:
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
}
}
}
这是java的:
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();
}
}
}
服务器的输出:
Spawning 1
s
s
l
l
scala
java
java的输出:
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
如您所见,我收到Echo (1)
的响应为空,我希望打印Echo (1)
我刚刚发送的字符串,您必须重新键入“Enter”以获取先前发送的字符串,这就是问题所在,我只需要来自服务器的一个响应像这样只有一次:Echo (1): some string
,我没有想法,我通过打印到控制台来跟踪它,但不知道发生了什么。
编辑:
预期客户的输出:
...
s
Echo (1): s
java
Echo (1): java
在预期的输出中,您无需重新输入enter
即可从服务器获取响应。
服务器的输出已经按预期工作。