Java与Java之间实时通信


============================================================================ 

服务器端: 
============================================================================

import java.net.InetAddress;   
import java.net.ServerSocket;   
import java.net.Socket;   
import java.util.Date;   
import java.util.ArrayList;   
import java.util.List;   
  
/**  
 * 服务器  
 *   
 * @author Johnson Lee  
 *   
 */  
public class Server {   
    private boolean running;   
    private List<ConnectedClient> clients;   
    private ServerSocket svrSocket;   
  
    public Server() {   
        this.running = true;   
        this.clients = new ArrayList<ConnectedClient>();   
    }   
  
    public boolean isRunning() {   
        return running;   
    }   
  
    public void run() {   
        try {   
            this.svrSocket = new ServerSocket(9090);   
            System.err.println("Server started on "  
                    + new java.sql.Date(new Date().getTime()));   
            while (running) {   
                Socket cltSocket = this.svrSocket.accept();   
                // 保存客户端的连接   
                InetAddress ip = cltSocket.getInetAddress();   
                int port = cltSocket.getPort();   
                ConnectedClient client = new ConnectedClient(ip, port);   
                this.clients.add(client);   
                System.err.println(ip + " connected.");   
                // 为每个客户端开一个线程   
                new Thread(new RequestProcessor(this, cltSocket)).start();   
            }   
        } catch (Exception e) {   
            this.running = false;   
        }   
    }   
  
    /**  
     * 连接到服务器端的客户端  
     *   
     * @author Johnson Lee  
     *   
     */  
    private static class ConnectedClient {   
        public InetAddress ip;   
        public int port;   
  
        public ConnectedClient(InetAddress ip, int port) {   
            super();   
            this.ip = ip;   
            this.port = port;   
        }   
  
        @Override  
        public boolean equals(Object obj) {   
            if (obj instanceof ConnectedClient) {   
                ConnectedClient c = (ConnectedClient) obj;   
                return c.ip.equals(this.ip) && c.port == this.port;   
            }   
            return false;   
        }   
    }   
  
    /**  
     * @param args  
     */  
    public static void main(String[] args) {   
        new Server().run();   
    }   
}  

import java.io.BufferedReader;    
import java.io.IOException;   
import java.io.InputStream;   
import java.io.InputStreamReader;   
import java.io.PrintWriter;   
import java.net.InetAddress;   
import java.net.Socket;   
import java.net.SocketException;   
  
/**  
 * 服务器端用于处理客户连接的处理器  
 *   
 * @author Johnson Lee  
 *   
 */  
public class RequestProcessor implements Runnable {   
    private Server server;   
    private Socket socket;   
  
    public RequestProcessor(Server server, Socket socket) {   
        this.server = server;   
        this.socket = socket;   
    }   
  
    @Override  
    public void run() {   
        if (this.server.isRunning() && this.socket != null  
                && this.socket.isConnected()) {   
            InetAddress ip = this.socket.getInetAddress();   
            BufferedReader br = null;   
            PrintWriter pw = null;   
            String line = null;   
            try {   
                InputStream is = this.socket.getInputStream();   
                br = new BufferedReader(new InputStreamReader(is));   
                pw = new PrintWriter(this.socket.getOutputStream(), true);   
                while ((line = br.readLine()) != null) {   
                    System.out.println(line);   
                    pw.println("服务器自动回复 ^_^ ");   
                    pw.flush();   
                }   
            } catch (SocketException e) {   
                System.err.println("客户端 " + ip + " 已断开连接");   
            } catch (IOException e) {   
                e.printStackTrace();   
            } finally {   
                try {   
                    if (br != null) {   
                        br.close();   
                        br = null;   
                    }   
                } catch (IOException e) {   
                }   
            }   
        }   
    }   
}  

============================================================================ 
客户端: 
============================================================================

import java.io.BufferedReader;    
import java.io.IOException;   
import java.io.InputStream;   
import java.io.InputStreamReader;   
import java.io.OutputStream;   
import java.io.PrintWriter;   
import java.net.InetSocketAddress;   
import java.net.Socket;   
  
/**  
 * 客户端  
 *   
 * @author Johnson Lee  
 *   
 */  
public class Client {   
    private InetSocketAddress svrAddress;   
    private Socket svrSocket;   
  
    public Client(String host, int port) {   
        this.svrAddress = new InetSocketAddress(host, port);   
    }   
  
    public void connect() throws IOException {   
        this.svrSocket = new Socket(svrAddress.getAddress(), svrAddress   
                .getPort());   
    }   
  
    public boolean isClosed() {   
        return this.svrSocket == null || this.svrSocket.isClosed();   
    }   
  
    public InputStream getInputStream() throws IOException {   
        return this.svrSocket.getInputStream();   
    }   
  
    public OutputStream getOutputStream() throws IOException {   
        return this.svrSocket.getOutputStream();   
    }   
  
    /**  
     * @param args  
     */  
    public static void main(String[] args) {   
        BufferedReader br = null;   
        PrintWriter pw = null;   
        String line = null;   
        try {   
            final Client c = new Client("127.0.0.1", 9090);   
            c.connect();// 连接服务器   
            try {   
                br = new BufferedReader(new InputStreamReader(System.in));   
                pw = new PrintWriter(c.getOutputStream(), true);   
                new Thread(new ResponseProcessor(c)).start();   
                while (!c.isClosed()) {   
                    line = br.readLine();   
                    pw.println(line);   
                }   
            } catch (IOException e) {   
                e.printStackTrace();   
            } finally {   
                try {   
                    if (br != null) {   
                        br.close();   
                        br = null;   
                    }   
                    if (pw != null) {   
                        pw.close();   
                        pw = null;   
                    }   
                } catch (IOException e) {   
                }   
            }   
        } catch (IOException e) {   
            e.printStackTrace();   
        }   
    }   
  
}  

 

import java.io.BufferedReader;    
import java.io.IOException;   
import java.io.InputStreamReader;   
import java.io.PrintWriter;   
import java.net.SocketException;   
  
/**  
 * 服务端响应处理器  
 *   
 * @author Johnson Lee  
 *   
 */  
public class ResponseProcessor implements Runnable {   
    private Client client;   
  
    public ResponseProcessor(Client c) {   
        super();   
        this.client = c;   
    }   
  
    @Override  
    public void run() {   
        BufferedReader br = null;   
        PrintWriter pw = null;   
        String line = null;   
        try {   
            br = new BufferedReader(new InputStreamReader(client   
                    .getInputStream()));   
            pw = new PrintWriter(System.out, true);   
            while (!client.isClosed()) {   
                line = br.readLine();   
                pw.println(line);   
            }   
        } catch (SocketException e) {   
            if (!client.isClosed()) {   
                System.err.println(e);   
            }   
        } catch (IOException e) {   
            e.printStackTrace();   
        }   
    }   
  
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值