[英]Socket unable to receive data
我有一個實現serversocket類的類,還有另一個實現客戶端1. Socket類的類。
所以我想做的是。 在獲取流之后,我希望客戶端向服務器發送一個號碼,然后服務器將依次響應客戶端是否是素數。 顯示在awt.Label
。
但是我無法收到任何回復。
這是客戶端構造函數的代碼:
public ClientIsPrime()
{
setLayout(new GridLayout(2,2));
add(new Label("Enter a number: "));
add(numEntry=new TextField(10));
add(checkPrime=new Button("Check if number is Prime"));
add(result=new Label("Result is shown here"));
try
{
Socket client = new Socket(InetAddress.getLocalHost(), 5959);
in=client.getInputStream();
out=client.getOutputStream();
}catch(UnknownHostException e)
{
result.setText("Local Host cannot be resolved");
}catch(IOException e)
{
result.setText("IOException occured");
}
checkPrime.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
try
{
int num;
num=Integer.parseInt(numEntry.getText());
out.write(num);
out.flush();
int c;
result.setText("");
String s="";
while((c=in.read())!=-1)
s+=((char)c);
result.setText(s);
}catch(IOException e)
{
result.setText("IOException occured");
}catch(NumberFormatException e)
{
result.setText("Please enter a valid number.");
}
}
});
}
服務器代碼:
public static void main(String args[])throws IOException
{
server=new ServerSocket(5959);
socket=server.accept();
System.out.println("connected");
InputStream in=socket.getInputStream();
OutputStream out=socket.getOutputStream();
int c; String numStr="";
while((c=in.read())!=-1)
numStr+=((char)c);
int num=Integer.parseInt(numStr);
if(num==3)
out.write("Number is Prime".getBytes());
else
out.write("Number is not Prime".getBytes());
out.flush();
in.close();
out.close();
}
這不是一個真正的應用程序。 我在學習。
一些問題。
首先,您的服務器實現將永遠不會退出while循環。 InputStream.read()
的API指出它將阻塞,直到接收到數據或關閉流為止。 流永遠不會關閉,因此在讀取初始數據后,讀取將永遠阻塞。
要解決此問題,您必須確定您的協議是什么。 見下文。
另一個問題是您正在從客戶端作為文本的解析int進行寫入。 因此說13(作為一個int)。 但是您正在閱讀它,好像它是一個字符序列一樣。 電線上的13將被讀取為某些控制字符。 您需要與如何寫入數據和讀取數據保持一致。
我的建議是制定一個基本協議。 在寫入端使用DataOutputStream
,在讀取端使用DataInputStream
,然后在兩側匹配讀寫調用,以確保您保持一致。
如果要通過導線發送整數,則在原始套接字流之上分層放置DataOutputStream / DataInputStream infinitely
容易,只需執行writeInt()和readInt()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.