URL类
构造方法
- public URL(String spec);
URL url=new URL(“http://www.nwsuaf.edu.cn/index.html”); - public URL(String protocol,String host,String file);
URL url=new URL(“http”,“www.163.com”,“index.html”);
常用方法
- public int getPort();
- public String getProcotol();
- public String getHost();
- public String getFile();
- public final inputStream openStream();//返回一个输入流,该输入流指向URL对象所包含的资源,通过该输入流可以将服务器上的资源信息读入到客户端
下面的程序实现了将百度的首页html文件读到本地
File outfile = new File("index.html");
URL url = new URL("http://www.baidu.com/");
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
BufferedWriter writer = new BufferedWriter(new FileWriter(outfile));
char buffer[] = new char[1000];
while (true) {
int len = reader.read(buffer);
if (len == -1)
break;
writer.write(buffer, 0, len);
}
writer.close();
reader.close();
InetAddress类
构造方法
通过调用InetAddress类的方法返回一个实例
InetAddress add1 = InetAddress.getLocalHost();//返回本地主机InetAddress对象
InetAddress add1 = InetAddress.getByName(String host); //获取指定主机名称的InetAddress对象
ServerSocket和Socket类
ServerSocket在服务器端使用,用于接收连接请求。
Socket类在服务端和客户端都要使用。
服务端创建的一般流程为:
- 创建ServerSocket实例并指定端口
- 调用ServerSocket的accept()方法获取连接请求(一个Socket实例)
- 调用Socket的getInputStream()方法获取输入流
客户端的一般流程为:
- 创建Socket实例并指定ip地址和端口
- 调用Socket的getOutputStream()方法获取输出流
下面是一个例子,实现了服务端接收多个客服端的消息并打印输出
每个Socket对象对应一个独立的线程
//服务端代码
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
ServerSocket server = null;
server = new ServerSocket(2022);
while (true) {
new clientThread(server.accept()).start();
}
}
}
class clientThread extends Thread {
private DataInputStream in;
public clientThread(Socket client) throws IOException {
in = new DataInputStream(client.getInputStream());
}
public void run() {
String str = null;
while (true) {
try {
str = in.readUTF();
} catch (IOException e) {
System.out.println(Thread.currentThread().getName() + "已下线");
try {
in.close();
} catch (IOException e1) {
e1.printStackTrace();
}
break;
}
if (str.equals("exit") || str == null)
break;
System.out.println(Thread.currentThread().getName() + ":" + str);
}
}
}
//客户端代码
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) throws IOException, InterruptedException {
// TODO Auto-generated method stub
Socket socket = null;
socket = new Socket("localhost", 2022);
DataOutputStream out = null;
out = new DataOutputStream(socket.getOutputStream());
while (true) {
try {
out.writeUTF("test message");
} catch (IOException e) {
e.printStackTrace();
out.close();
break;
}
Thread.sleep(1000);
}
socket.close();
}
}
3万+

被折叠的 条评论
为什么被折叠?



