Recive套接字数据java

时间:2015-10-26 13:58:08

标签: java sockets

为什么它不从服务器和客户端到服务器重新传输数据?我的方法" 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);
   }

   }

1 个答案:

答案 0 :(得分:1)

我不知道您调用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");
       }
}