package socket;
//这是服务端的代码
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Server implements Runnable{
Socket socket;
public Server(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
System.out.println(socket.getInetAddress());
try {
InputStream inputStream=socket.getInputStream();
byte buf[]=new byte[1024];
int length=0;
length=inputStream.read(buf);
System.out.println(new String(buf,0,length));
OutputStream outputStream=socket.getOutputStream();
PrintWriter printWriter=new PrintWriter(outputStream);
printWriter.println("<html><head></head><body><font size='30' color='red'>你好</font></body></html>");
printWriter.flush();
socket.shutdownInput();
System.out.println("发送数据成功");
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception {
ServerSocket serverSocket=new ServerSocket(9090);
while(true)
{
Socket socket=serverSocket.accept();
Thread t=new Thread(new Server(socket));
t.start();
}
}
}
通过浏览器访问服务端,可以正常访问,不过运行的下面客户端的代码就抛出
java.io.IOException: Invalid Http response
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at socket.Client.main(Client.java:17)
//这是客户端的代码
package socket;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
public class Client {
public static void main(String[] args) {
try {
URL url=new URL("http://192.168.0.105:9090/");
URLConnection h =url.openConnection();
InputStream inputStream=h.getInputStream();
byte[] buf=new byte[1024];
int length=0;
length=inputStream.read(buf);
System.out.println(new String(buf,0,length));
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
|