2014-10-05 71 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

相關問題