我下面從Java網絡編程的例子,並決定分別寫在Java的斯卡拉客戶端 - 服務器,這裏的Scala代碼:斯卡拉和Java IO和插座問題
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
正如你所看到的IM接收Echo (1)
響應空在那裏我希望打印Echo (1)
加上字符串我只是發,你得重新輸入「Enter」來獲取字符串previouly發送,所以這就是問題所在,我只需要一次這樣的服務器響應:Echo (1): some string
,我出來的想法,我跟蹤它打印到控制檯,但無法弄清楚發生了什麼事。
編輯:
預計客戶端的輸出:
...
s
Echo (1): s
java
Echo (1): java
在不必重新輸入enter
得到來自服務器的響應與預期輸出。
服務器的輸出已按預期工作。
你的問題是最不清楚的。我建議你以與實際產出相同的形式添加預期產出。 – EJP