Java中的简单TCP

时间:2015-11-28 14:20:24

标签: java tcp

我开始学习使用java进行网络编程。这是我的第一个,但似乎我做不到。 断绝:

public class Server1 {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        try {
            ServerSocket server = new ServerSocket(2508);
            Socket client = server.accept();
            System.out.println("Connected");
            while(true){
                BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream()));
                BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
                String str = br.readLine();
                int num = Integer.parseInt(str);
                if(num%2==0){
                    bw.write("Even");
                }else{
                    bw.write("Odd");
                }
                bw.newLine();
                bw.flush();

            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}

客户:

public class EvenOddClient1 {
    public static void main(String[] args) {
        try {
            Socket client = new Socket("Localhost", 2508);
            while(true){
                Scanner s = new Scanner(System.in);
                BufferedWriter bw = new BufferedWriter(
                        new OutputStreamWriter(client.getOutputStream()));
                BufferedReader br = new BufferedReader(
                        new InputStreamReader(client.getInputStream()));
                int num = s.nextInt();
                bw.write(num);
                bw.newLine();
                bw.flush();
                String str = br.readLine();
                System.out.println(str);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
}

我认为我的代码无法从客户端读取数字。谢谢你的帮助

1 个答案:

答案 0 :(得分:2)

您将在客户端中以二进制格式(作为int)发送整数:

int num = s.nextInt();
bw.write(num);

并且您将其视为服务器中的字符串:

String str = br.readLine();
int num = Integer.parseInt(str);

在与客户端发送" 3" (例如)时导致服务器出错:

Exception in thread "main" java.lang.NumberFormatException: For input string: ""
    at java.lang.NumberFormatException.forInputString(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at Server1.main(Server1.java:21)

关闭连接。

在您的客户端中,请执行此操作,将int作为String发送:

int num = s.nextInt();
bw.write( new Integer( num ).toString() );