2015-11-18 4 views
0

Итак, я пытаюсь прочитать данные из сокета. Я установил соединение и отправил сообщение другому сокету, который его прослушивает, но, похоже, ничего не получает. код клиента:Чтение данных из сокета java

import java.net.*; 
import java.io.*; 
import java.util.*; 
public class TCPClient { 
/*Conecting to server. 
*/ 
public static void Client(String[] args){ 
    int port = 47361; 
    Scanner in = new Scanner(System.in); 
    System.err.print("Starting up..."); 
    Socket CS1 = null; //Declaring CS1 as a socket 
    DataOutputStream DOS1 = null; //Declaring an outputput data stream "DOS1" 
    DataInputStream DIS1 = null; //Setting the values to null 
    System.err.println("All created."); 
    System.out.println("---------"); 
    System.out.println(" OPTIONS"); 
    System.out.println("---------"); 
    System.out.println("0. Connect."); 
    System.out.println("1. Change port."); 
    System.out.println("2. Cancel start-up."); 
    System.out.println(""); 
    System.out.println("Choose an option."); 
    try { 
    short ans = in.nextShort(); 
    if (ans == 2){ 
    System.err.println("System.exit(0)"); 
    System.exit(0); 
    } 
    if (ans == 1){ 
    System.out.print("Enter the new port: "); 
    port = in.nextInt(); 
    ans = 0; 
    } 
    if (ans == 0){ 
    System.out.print("Enter the IP: "); 
    CS1 = new Socket(in.next(), port); //Creating an instane of the "CS1" socket 
    System.err.print("Request sent on port " + port + "."); 
    DOS1 = new DataOutputStream(CS1.getOutputStream()); 
    DIS1 = new DataInputStream(CS1.getInputStream()); //creating output and input streams 
    System.err.println("Instances created!"); 
    if (DIS1 != null){ 
    System.err.println("DIS1 is connected!"); 
    } 
    else { 
    System.err.println("DIS1 is null!"); 
    } 
    if (DOS1 != null) { 
    System.err.println("DOS1 is connected!"); 
    System.out.print("Enter input: "); 
    String FirstMessage = in.nextLine(); 
    DOS1.writeBytes(FirstMessage); 
    String SecondMessage = DIS1.readLine(); 
    System.out.println(SecondMessage); 
    if (SecondMessage.equals(FirstMessage)) { 
    } 
    else { 
     System.out.println("Please check the code, FirstMessage != SecondMessage"); 
     } 
    } 
    else { 
    System.err.println("DOS1 is null!"); 
    } 
    if (CS1 != null) { 
    System.err.println("CS1 is connected!"); 
    } 
    else { 
    System.err.println("CS1 is null!"); 
    } 
    DIS1.close(); 
    DOS1.close(); 
    CS1.close(); //closing everything 
    } 
    } 
    catch (IOException e){ 
    System.err.println("IOException: " + e.getMessage()); 
    } 
} 
} 

Серверный код:

import java.net.*; 
import java.io.*; 
import java.util.*; 
public class TCPServer { 
/*Connecting to client 
    */ 
public static void Server (String[] args) { 
    System.err.print("Starting up..."); 
    ServerSocket SS1 = null; 
    DataOutputStream DOS1 = null; 
    DataInputStream DIS1 = null;//Setting the values to null 
    System.err.println("All created."); 
    Scanner in = new Scanner(System.in); 
    try { 
    SS1 = new ServerSocket(47361); //setting the socket SS1 to port 5000 and creating an instance 
    System.err.print("Listening on port 47361..."); 
    Socket CS1 = SS1.accept(); //accepting the connection request 
    DOS1 = new DataOutputStream(CS1.getOutputStream()); 
    DIS1 = new DataInputStream(CS1.getInputStream());//creating output and input streams 
    System.err.println("Instances created!"); 
    if (DIS1 != null){ 
    System.err.println("DIS1 is connected!"); 
    System.err.println(DIS1); 
    } 
    else { 
    System.err.println("DIS1 is null!"); 
    } 
    if (DOS1 != null) { 
    System.err.println("DOS1 is connected!"); 
    System.err.println(DOS1); 
    } 
    else { 
    System.err.println("DOS1 is null!"); 
    } 
    if (SS1 != null) { 
    System.err.println("SS1 is connected!"); 
    System.err.println(SS1); 
    } 
    else { 
    System.err.println("SS1 is null!"); 
    } 
    String FirstMessage = null; 
    FirstMessage = DIS1.readLine(); 
    System.out.println(FirstMessage); 
    String SecondMessage = FirstMessage; 
    DOS1.writeBytes(SecondMessage); 
    DIS1.close(); 
    DOS1.close(); 
    SS1.close(); //closing everything 
    } 
    catch (IOException error){ 
    System.err.println("IOException " + error.getMessage()); 
    } 
catch (java.util.InputMismatchException error2){ 
    System.err.println("IOException " + error2.getMessage()); 
    } 
} 
} 

Это довольно много EchoServer до сих пор, не Buffered. Я посмотрел в отладчике, и он застрял на линии FirstMessage = DIS1.readLine(); на сервере и String SecondMessage = DIS1.readLine(); на клиенте. Кроме того, как сервер, так и клиент ждут ввода даже после ввода любого возможного ввода. Почему это случается? И как я могу это сделать?

Замечание: Я знаю, что поток i/o или сокет не будут, когда-либо равными нулю. Кроме того, компилятор предупреждает меня, что класс java.io.DataInputStream устарел. Какие другие классы вы рекомендуете использовать?

Другая сторона Примечание: Я новичок в IO, пожалуйста, не убивайте меня об этом ха-ха :)

Спасибо!

+0

Результат 'new' не может быть null, если нет исключения. Все те тесты для null совершенно бессмысленны. – EJP

+0

Да, я упомянул, что знаю это. _ «Замечание: я знаю, что поток i/o или сокет не будет, когда-либо равным нулю». _ –

+0

Это неправда, и это не то, что я сказал. Он может быть нулевым, но не в тех местах, где вы его тестируете. Не загромождайте свой код бессмысленным мусором. – EJP

ответ

1

Обычная проблема. Вы читаете строки, но вы не пишете строки. Добавьте строковый терминатор в сообщение при записи.

+0

Я сделал 'String FirstMessage = in.nextLine() +" \ n \ r ";' и перезапустил программу: он напечатал строку 'Enter input: null'. Что, почему и как? –

+0

Терминаторы строк, распознанные 'readLine()', являются '\ n',' \ r' и '\ r \ n'. См. Javadoc. Тот, который вы использовали, не является терминатором линии на любой компьютерной системе, которую я когда-либо использовал с 1971 года. См. [Здесь] (http://stackoverflow.com/questions/3307747/difference-between-newline-and-carriage-return- r/3315133? s = 1 | 0.8320 # 3315133), почему бы и нет. – EJP

+0

Так что мне нужно использовать 'String FirstMessage = in.nextLine() + "\ r \ n";' ? –

Смежные вопросы