服務端
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循環那裡;
主要想問一下為什麼會報這樣的錯,改進可以不要,
但是如果我用浏覽器訪問這個服務器,卻不會報錯,這是為什麼呢,
這裡主要問一下為什麼會出這樣的錯,改進可以不要。
在你的這段代碼裡,犯了兩個錯誤
public class Client {
public static void main(String[] args) throws IOException{
Socket socket=new Socket(InetAddress.getLocalHost(),9999);
BufferedWriter writer=new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream()));
writer.write("我是");
writer.flush();
writer.close();
socket.close();
}
}
BufferedReader reader=new BufferedReader(
new InputStreamReader(socket.getInputStream()));
while((str=reader.readLine()).length()>0)
{
msg.append(str);
msg.append("\r\n");
}
建議將while的循環條件改為:
BufferedReader reader=new BufferedReader(
new InputStreamReader(socket.getInputStream()));
while((str=reader.readLine()) != null)
{
msg.append(str);
msg.append("\r\n");
}
在readLine方法中,若無內容返回null而不是空字符串。希望你在編程的時候,養成資源釋放的好習慣