[英]Recive socket data java
為什么它不從服務器和從客戶端到服務器接收數據? 我的方法“odbierz”不好? 我想將數據從服務器發送到客戶端,然后客戶端在更改時將數據發送到服務器。
客戶類
public class Klient {
private Socket sock;
private PrintWriter out;
private BufferedReader in;
public Klient() throws UnknownHostException, IOException
{
sock=new Socket("localhost",50007);
System.out.println("Nawiazalem polaczenie: "+sock);
in=new BufferedReader(new InputStreamReader(sock.getInputStream()));
out=new PrintWriter(sock.getOutputStream(), true);
}
public void wyslijDane(int numerKart) throws IOException
{
System.out.print("<Wysylamy:> ");
out.print(numerKart);
out.flush();
System.out.println("Wyslano kartę" + numerKart);
}
public void odbierz() throws IOException
{
String str;
if(in.ready())
{
while(true)
{
str=in.readLine();
System.out.println("<Nadeszlo:> " + str);
}
}
else
System.out.println("Zajetre");
}
public static void main(String[] args) throws IOException
{
}
}
public class Server
{
public static final int PORT=50007;
private ServerSocket server;
private Socket sock;
private PrintWriter out;
private BufferedReader in;
public Server() throws IOException
{
server=new ServerSocket(PORT);
System.out.println("Nasluchuje: "+ server);
sock=server.accept();
System.out.println("Jest polaczenie: "+sock);
in=new BufferedReader(new InputStreamReader(sock.getInputStream()));
out=new PrintWriter(sock.getOutputStream(), true);
public void wyslijDane(int numerKarty ) throws IOException
{
System.out.print("<Wysylamy:> ");
out.print(numerKarty);
out.flush();
System.out.println("Wyslano kartę" + numerKarty);
}
}
我不知道您如何以及在何處調用odbierz()
方法,但是while(true)
是一個無限循環,這可能就是您的程序無法運行的原因。
嘗試刪除循環:
public void odbierz() throws IOException {
String str;
if(in.ready()) {
str=in.readLine();
System.out.println("<Nadeszlo:> " + str);
} else {
System.out.println("Zajetre");
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.