简体   繁体   English

具有ReadLine异常的Java处理中的套接字编程

[英]Socket Programming in Java Handling with ReadLine Exception

I am new to socket programming and trying to figure out an exception handling problem. 我是套接字编程的新手,正在尝试找出异常处理问题。 I can't send a string message to a server from a client in java because the readLine part of my code gives exception error when I run the program. 我无法从java中的客户端向服务器发送字符串消息,因为在运行程序时,代码的readLine部分给出了异常错误。 I tried throwing Exception in my Server class and get no red underlined code error while running the server program, but when I run the client program after server program, I got exception error in the br.readLine section of my code. 我尝试在服务器类中抛出Exception,并且在运行服务器程序时没有出现红色带下划线的代码错误,但是当我在服务器程序之后运行客户端程序时,在代码的br.readLine部分中出现了异常错误。 What might be the cause? 可能是什么原因?

My client code: 我的客户代码:

package com.soc;
import java.io.OutputStreamWriter; 
import java.io.PrintWriter;
import java.net.Socket;

public class socClient {

public static void main(String[] args) throws Exception{

    String ip = "localhost";
    int port = 9999;// 0-1023 to 65535
    Socket s = new Socket(ip,port);

    String str = "Hello World";

    OutputStreamWriter os = newOutputStreamWriter(s.getOutputStream());

    PrintWriter out = new PrintWriter(os);
    os.write(str);
    os.flush(); 
}

} }

My server code: 我的服务器代码:

package com.soc;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

public class socServer {

public static void main(String[] args) throws Exception{

    System.out.println("Server is started");
    ServerSocket ss = new ServerSocket(9999);

    System.out.println("Server is waiting for client request");
    Socket s = ss.accept();

    System.out.println("Client connected");


    BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
    String str = null;
    str = br.readLine();

    System.out.println("Client Data: " +str);
}

} }

原因是客户端永远不会关闭套接字,这会导致在某些操作系统上重置连接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM