[英]Server is not sending the response in java using socket programming
當我從客戶端向服務器發送一些數據時,服務器沒有給我響應。 當我輸入所有數據直到性別時,cursor 在那里閃爍。 似乎它希望用戶插入更多數據。 它接受的數據與我插入的數據一樣多。 我在下面提供了我的所有代碼
我的客戶端代碼是
import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;
import java.util.Scanner;
public class Client {
public static void main(String[] args) throws IOException {
int age,carPrice,temp,temp1;
String gender, s_temp;
Scanner sc = new Scanner(System.in);
Socket socket = new Socket("127.0.0.1",1342);
Scanner sc1 = new Scanner(socket.getInputStream());
PrintStream p = new PrintStream(socket.getOutputStream(), true);
System.out.println("Enter Your Age: ");
age = sc.nextInt();
p.println(age);
System.out.println("Enter the Cost of Vehicle: ");
carPrice = sc.nextInt();
p.println(carPrice);
System.out.println("Enter Your Gender: ");
gender = sc.next();
p.println(gender);
p.flush();
temp = sc1.nextInt();
System.out.println(temp);
s_temp = sc1.next();
System.out.println("The Gender is: " + s_temp);
temp1 = sc1.nextInt();
System.out.println(temp1);
socket.close();
}
}
我的服務器端代碼:
public class Server {
public static void main(String args[]) throws IOException, SQLException{
ServerSocket ssocket = null;
Socket socket = null;
System.out.println("Server Listening.......*");
ssocket=new ServerSocket(1342);
while(true){
try{
socket = ssocket.accept();
System.out.println("Connection Established.");
ServerThread st = new ServerThread(socket);
st.start();
}
catch(Exception e){
System.out.println("Connection Error....");
}
}
}
}
class ServerThread extends Thread{
Socket s1 =null;
Scanner sc = null;
PrintStream p=null;
int age,carPrice,temp;
String gender,temp1;
public ServerThread(Socket s){
s1=s;
}
public void run(){
try{
sc = new Scanner(s1.getInputStream());
p = new PrintStream(s1.getOutputStream(),true);
age = sc.nextInt();
gender = sc.next();
carPrice = sc.nextInt();
p.println(age*2);
p.println(carPrice);
p.println("Your gender is: " +gender);
s1.close();
System.out.println("Connection Closed....");
}
catch(Exception e){
}
}
}
告訴我為什么我的服務器沒有發送響應。 更正它,以便它可以向客戶端發送響應。
年齡、汽車價格和性別輸入,不與發送訂單一起閱讀。 必須按順序從客戶端讀取。
更改以下代碼段。 此外,添加sc.nextLine()
以在 int 讀取后跳過換行符。
服務器
age = sc.nextInt();
carPrice = sc.nextInt();
sc.nextLine(); // skip newline
gender = sc.next();
... 代替
age = sc.nextInt();
gender = sc.next();
carPrice = sc.nextInt();
在客戶端,讀取順序與發送順序不匹配。 sc.next()
也讀取一個單詞,但是您在發送性別時發送了很多單詞。 所以你必須用sc.nextLine()
改變方法
客戶
temp = sc1.nextInt();
System.out.println(temp);
temp1 = sc1.nextInt();
System.out.println(temp1);
sc1.nextLine(); // skip newline
s_temp = sc1.nextLine();
System.out.println("The Gender is: " + s_temp);
.. 代替
temp = sc1.nextInt();
System.out.println(temp);
s_temp = sc1.next();
System.out.println("The Gender is: " + s_temp);
temp1 = sc1.nextInt();
System.out.println(temp1);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.