2014-10-05 68 views
1

我正在使用TCP/IP在java中编写客户端服务器程序。为此目的,我写了下面的代码:无法从客户端获取客户端服务器程序中的消息java

serversock.java:

import java.net.*; 
import java.io.*; 

public class serversock { 
    public static void main(String[] args) throws IOException 
    { 
     ServerSocket sersock = null; 

     try 
     { 
      sersock = new ServerSocket(10007); 
     } 

     catch (IOException e) 
     { 
      System.out.println("Can't listen to port 10007"); 
      System.exit(1); 
     } 

     Socket clientSocket = null; 
     System.out.println("Waiting for connection...."); 


     try 
     { 
      clientSocket = sersock.accept(); 
     } 

     catch (IOException ie) 
     { 
      System.out.println("Accept failed.."); 
      System.exit(1); 
     } 

     System.out.println("Conncetion is established successfully.."); 
     System.out.println("Waiting for input from client..."); 

     PrintWriter output = new PrintWriter(clientSocket.getOutputStream()); 

     BufferedReader input = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); 
     String inputLine = input.readLine(); 

     while (inputLine != null) 
     { 
      output.println(inputLine); 
      System.out.println("Server: " + inputLine); 
      inputLine = input.readLine(); 
     } 
     input.close(); 
     clientSocket.close(); 
     sersock.close(); 

    } 
} 

clientsock.java:

import java.util.*; 
import java.io.*; 
import java.net.*; 

public class clientsock 
{ 
    public static void main(String[] args) throws IOException 
    { 
     Socket sock = new Socket("localhost",10007); 

     // Scanner scan = new Scanner(System.in); 
     PrintWriter output = new PrintWriter(sock.getOutputStream(),true); 
     BufferedReader input = new BufferedReader(new InputStreamReader(sock.getInputStream())); 
     String line = null; 

     BufferedReader stdInput = new BufferedReader(new InputStreamReader(System.in)); 

     System.out.println("Enter data to send to server: "); 
     line = stdInput.readLine(); 
     while ((line) != "bye") 
     { 
      output.println(line.getBytes()); 
      line = stdInput.readLine(); 
      System.out.println("Server sends: " + input.read()); 
     } 
     sock.close(); 

    } 
} 

现在上运行的程序,我得到了以下的输出: 服务器:

[email protected]:~/Documents/java$ java serversock 
Waiting for connection.... 
Conncetion is established successfully.. 
Waiting for input from client... 
Server: [[email protected] 
[email protected]:~/Documents/java$ 

客户端:

[email protected]:~/Documents/java$ java clientsock 
Enter data to send to server: 
qwe 
sdf 
^[email protected]:~/Documents/java$ 

服务器正在接收不同的符号,客户端什么也没收到。请帮我解决它。

回答

0

在客户端替换:

output.println(line.getBytes()); 

output.println(line); 
+0

但它不会修复所有问题.. – learner 2014-10-05 01:37:16

+1

是的,你有很多的问题。找到一个调试器...尝试下载netbeans并在循环内设置一个断点...看看实际发生了什么。 – fodon 2014-10-05 01:49:25

相关问题