![](/img/trans.png)
[英]Why is my server (runs in thread) not recieving the DatagramPackage?
[英]Why is my server program not recieving the command?
服務器代碼:
try{
ServerSocket guard=new ServerSocket(6600);
StackCalculator SC=new StackCalculator();
while(true){
SC.currentSocket=guard.accept();
Socket currentSocket;
Scanner s=new Scanner(currentSocket.getInputStream());
PrintWriter pw=new PrintWriter(currentSocket.getOutputStream());
String request=s.nextLine();
int num=Integer.parseInt(s.nextLine());
int reply=PerformCalculation(request,num);//method to perform calculation
pw.println(reply);
pw.flush();
}
客戶代碼:
try{
Socket sc=new Socket("localhost",6600);
Scanner s=new Scanner(sc.getInputStream());
PrintWriter pw=new PrintWriter(sc.getOutputStream());
pw.print("ROOT 4");
pw.flush();
String response=s.nextLine();
System.out.println(response);
pw.close();
sc.close();
}
這是代碼的一部分。 客戶端正在連接到服務器,並且也正在傳遞請求。 但是服務器未從掃描儀讀取它。
您甚至都不會初始化“ currentSocket”,這意味着您嘗試執行此操作時應獲取NullPointerException:“ currentSocker.getInputStream()”,因為您在SC.currentSocket上執行了guard.accept(),這不是currentSocket。
另外,如評論員所建議的那樣,您永遠不會在調用時從服務器發送整行:
pw.print("ROOT 4");
pw.flush();
你應該在哪里打電話
pw.println("ROOT 4");
pw.flush();
而且您還在服務器上讀取多行內容-對我來說似乎是一個錯誤。
客戶端和服務器上都有一些錯誤。您正在使用Socket currentSocket;
從來沒有初始化過。 在服務器代碼上,您正在接受來自客戶端bt的2個輸入。客戶端僅提供了一個輸入。i修復了服務器端和客戶端代碼,您可能想嘗試一下。
while(true){
Socket currentSocket = guard.accept();
Scanner s=new Scanner(currentSocket.getInputStream());
PrintWriter pw=new PrintWriter(currentSocket.getOutputStream());
String request=s.nextLine(); //****accepting first input
int num=Integer.parseInt(s.nextLine()); //****accepting second input program is stuck here
int reply=PerformCalculation(request,num);//method to perform calculation
pw.println(reply);
pw.flush();
}
//客戶端代碼
try{
Socket sc=new Socket("localhost",6600);
Scanner s=new Scanner(sc.getInputStream());
PrintWriter pw=new PrintWriter(sc.getOutputStream());
pw.println("ROOT 4"); //giving out the first input
pw.println("123");//giving out the second input - should be a number server is expecting a int.
pw.flush();
String response=s.nextLine();
System.out.println(response);
pw.close();
sc.close();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.