我正在学习TCP/IP协议(protocol),昨天我写了一个程序。这是一个简单的代码,客户端发送一个字符串,服务器接收并将其打印到控制台。但是当我开始的时候,这变成了错误。请有人为我检查。这是我的代码。
客户端 :
public class Client {
Socket client ;
DataInputStream is;
DataOutputStream os;
public Client(){
try {
client=new Socket("localhost", 7777);
} catch (IOException ex) {
Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void send(String txt){
try {
os=new DataOutputStream(client.getOutputStream());
if(os!=null && client!=null)
os.writeBytes(txt);
System.out.println("Send OK");
close();
} catch (IOException ex) {
Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void close(){
if(client!= null&& os!= null&& is!= null) {
try{
os.close();
is.close();
client.close();
}
catch(UnknownHostException e) {
System.err.println(e);
} catch(IOException e) {
System.err.println(e);
}}}}
客户主体:
public static void main(String[] args) {
// TODO code application logic here
Client client=new Client();
client.send("hehea");
}
和服务器:
public class ServerTCP {
PrintStream os;
DataInputStream is;
Socket client;
ServerSocket myserver;
public void open(){
try {
myserver=new ServerSocket(7777);
System.out.println("Open Server ");
client=myserver.accept();
listen();
} catch (IOException ex) {
Logger.getLogger(ServerTCP.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void listen(){
try {
System.out.println("\nListenning....");
is=new DataInputStream(client.getInputStream());
os=new PrintStream(client.getOutputStream());
String txt="";
ReverseString result = null;
while(true)
{
result=new ReverseString(is.readLine());
System.out.println(is.readLine());
}
} catch (IOException ex) {
Logger.getLogger(ServerTCP.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
服务器主
public static void main(String[] args) {
// TODO code application logic here
ServerTCP server=new ServerTCP();
server.open();
最后,控制台错误
java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(SocketInputStream.java:196)
at java.net.SocketInputStream.read(SocketInputStream.java:122)
at java.net.SocketInputStream.read(SocketInputStream.java:210)
at java.io.DataInputStream.readLine(DataInputStream.java:513)
at daochuoiservertcp.ServerTCP.listen(ServerTCP.java:50)
at daochuoiservertcp.ServerTCP.open(ServerTCP.java:34)
at daochuoiservertcp.Server.main(Server.java:21)
最佳答案
\n
。 关于java - java.net.SocketException : Connection reset ,任何人都可以帮助我,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25903240/