Connection reset by peer: socket write error

我是小明哥哥 我是小明哥哥 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
小弟最近练习Java socket tcp这部分.出了点问题。客户端给服务器发送信息。第一次服务器可以收到,但是客户端第二次发送,就报异常了:Exception in thread "main" java.net.SocketException: Connection reset by peer: socket write error


具体代码如下:

Server.java


import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {

private ServerSocket sskt=null;
public static final int port=9999;



public ServerSocket getSskt() {
return sskt;
}



public Server() {
try {
sskt=new ServerSocket(9999);
System.out.println("服务器启动成功..."+"端口号:"+port);
} catch (IOException e) {
e.printStackTrace();
}
}

public Socket acceptSkt() throws IOException{
Socket skt=null;
skt=getSskt().accept();
System.out.println("一个客户端程序已连接."+"clientInfo:"+skt.getInetAddress().getHostAddress()+"-->"+skt.getPort());
return skt;

}

public String readMsg(Socket skt) throws IOException{
InputStream ins=skt.getInputStream();
DataInputStream dis=new DataInputStream(ins);
String msg= dis.readUTF();
System.out.println("客户端发来的信息:"+msg);
return msg;
}


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

Server server=new Server();
Socket skt= server.acceptSkt();
String msg=server.readMsg(skt);

}

}

client.java


import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.UnknownHostException;

public class Client {
public static final String host = "127.0.0.1";
public static final int port = 9999;
private Socket skt = null;
private DataOutputStream dos = null;

public DataOutputStream getDos() {
return dos;
}

public Client() {
try {
skt = new Socket(host, port);
dos = new DataOutputStream(skt.getOutputStream());
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

}

public String getMsgFrmConsole() throws IOException {
System.out.print("请输入:");
BufferedReader bufReader = new BufferedReader(new InputStreamReader(
System.in));
String msg = null;
msg = bufReader.readLine();
return msg;
}

public void sendmsg(String msg) throws IOException {

getDos().writeUTF(msg);
getDos().flush();

}

public String reviceMsg() throws IOException {
return null;
}

public static void main(String[] args) throws UnknownHostException,
IOException {

Client client = new Client();
while (true) {
String msg = client.getMsgFrmConsole();
client.sendmsg(msg);
}

}

}
在此感谢大家的帮助了
...全文

相关推荐

评论 5
收藏 已收藏
分享
返回顶部
我是小明哥哥
Java SE 62,620 成员 307,251 内容