1.URL
有时间把这么想明白 这种操作流的过程
public static void main(String[] args)throws Exception{
URL url = new URL("http://www.baidu.com");
InputStreamReader isr = new InputStreamReader(url.openStream());
BufferedReader br = new BufferedReader(isr);
String s;
while((s = br.readLine()) != null){
System.out.println(s);
}
br.close();
}
还有一种方式,就是给服务器传数据,然后服务器会送给客户端数据。上面是最简单的一种。
2.Socket
- 服务多个用户(TCP实现)
package com.dgg.socket2;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
class ServerWorker extends Thread{
private Socket socket;
private BufferedReader in;
private PrintWriter out;
public ServerWorker(Socket s) throws IOException{
socket = s;
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()), true);
start();
}
public void run(){
try {
while(true){
String str = in.readLine();//从in读数据
if(str.equals("END"))
break;
System.out.println("来自客户端: " + str);
out.println(str);
Thread.sleep(3000);//将来自客户端的数据,原封不动传回
}
System.out.println("关闭...");
}catch (IOException e){
}catch (InterruptedException e){
e.printStackTrace();
}finally {
try{
socket.close();
}catch (IOException e){
}
}
}
}
public class ServerSocketMult {
static final int ROPT = 8080;
public static void main(String[] args) throws IOException{
ServerSocket s = new ServerSocket(ROPT);
System.out.println("启动服务器");
try{
while(true){
Socket socket = s.accept();
try{
new ServerWorker(socket);
}catch (IOException e){
socket.close();
}
}
}finally {
s.close();
}
}
}
package com.dgg.socket2;
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
class ClientSocketMultThread extends Thread {
private Socket socket;
private BufferedReader in;
private PrintWriter out;
private static int counter = 0;
private int id = ++ counter;
public static int threadCount(){
return counter;
}
public ClientSocketMultThread(InetAddress addr){
System.out.println("创建客户端: " + id);
try{
socket = new Socket(addr, ServerSocketMult.ROPT);
}catch (IOException e){
}
try{
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()), true);
start();
}catch (IOException e){
try{
socket.close();
}catch (IOException e2){
}
}
}
public void run(){
try{
for (int i = 0; i < 5; i++) {
out.println("客户端 " + id + ": 消息 " + i);//向out写数据
String str = in.readLine();//从in读返回的数据
System.out.println("来自服务器: " + str);
}
out.println("END");
}catch (IOException e){
}finally {
try{
socket.close();
}catch (IOException e){
}
}
}
}
public class ClientSocketMult {
static final int MAX_THREAD = 10;
public static void main(String[] args) throws IOException, InterruptedException{//内部类里不能出现static声明
InetAddress addr = InetAddress.getByName(null);
while(true){
if(ClientSocketMultThread.threadCount() < MAX_THREAD){
new ClientSocketMultThread(addr);
}
Thread.sleep(5000); //每5秒建一个客户端?访问自己加的服务器
}
}
}
- 数据报通信(UDP)