WANGYANG000001
2016-01-10 05:00
采纳率: 50%
浏览 1.4k
已采纳

关于java的Socket的一个问题

服务端

package 手写服务器一;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
//////////////////
public class Server {
private ServerSocket server;

public static void main(String[] args) {
    Server s=new Server();
    s.start();
}
//创建客户端
private void start(){
    try {
        server=new ServerSocket(9999);
        this.receive();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
//接收数据
private void receive(){
    try {
        Socket socket=server.accept();
        StringBuilder msg=new StringBuilder();
        String str=null;
        BufferedReader reader=new BufferedReader(
                new InputStreamReader(socket.getInputStream()));
        while((str=reader.readLine()).length()>0)
        {
            msg.append(str);
            msg.append("\r\n");
        }
        System.out.println(msg.toString());
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

}

客户端
package 客户端;
///////////
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.Socket;
////////////
public class Client {
public static void main(String[] args) throws IOException{
@SuppressWarnings("resource")
Socket socket=new Socket(InetAddress.getLocalHost(),9999);
BufferedWriter writer=new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream()));
writer.write("我是");
writer.newLine();
writer.flush();
}
}
//////////
错误为:java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(Unknown Source)
at java.net.SocketInputStream.read(Unknown Source)
at sun.nio.cs.StreamDecoder.readBytes(Unknown Source)
at sun.nio.cs.StreamDecoder.implRead(Unknown Source)
at sun.nio.cs.StreamDecoder.read(Unknown Source)
at java.io.InputStreamReader.read(Unknown Source)
at java.io.BufferedReader.fill(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
at 手写服务器一.Server.receive(Server.java:34)
at 手写服务器一.Server.start(Server.java:20)
at 手写服务器一.Server.main(Server.java:14)
///////////////
客户端访问会报上面的错误,错误在服务端的接收数据的while循环那里;
主要想问一下为什么会报这样的错,改进可以不要,
但是如果我用浏览器访问这个服务器,却不会报错,这是为什么呢,
这里主要问一下为什么会出这样的错,改进可以不要。

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

3条回答 默认 最新

相关推荐 更多相似问题