你的位置:首页 > Java教程

[Java教程]Java Socket 连接 Client端 和 Server端


Client端:


import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

public class ChatClient {
    private static final String SERVER_IP = "127.0.0.1";
    private static final int SERVER_PORT = 8888;
    
    Socket socket = null;
    DataOutputStream dos = null;
    DataInputStream dis = null;
    private boolean bConnected = false;

    private static Scanner in = new Scanner(System.in);
    private static String hostInfo = null;

    Thread tRecv = new Thread(new RecvThread());

    public static void main(String[] args) {
        new ChatClient().launch();
    }

    public void launch() {
        connect();
        tRecv.start();
    }

    public void connect() {
        try {
            socket = new Socket(SERVER_IP, SERVER_PORT);
            dos = new DataOutputStream(socket.getOutputStream());
            dis = new DataInputStream(socket.getInputStream());
            bConnected = true;

            InetAddress addr = InetAddress.getLocalHost();
            String ip = addr.getHostAddress().toString();// 获得本机IP
            String address = addr.getHostName().toString();// 获得本机名称
            hostInfo = ip + "\t" + address + "\tconnected.";
            System.out.println(hostInfo);
            dos.writeUTF(hostInfo);
            dos.flush();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void disconnect() throws IOException {
        try {
            dos.close();
            dis.close();
            socket.close();
        } catch (IOException e) {
        }
    }

    private class RecvThread implements Runnable {
        public void run() {
            while (bConnected) {
                try {
                    if (in.hasNext()) {
                        String talk = in.nextLine();
                        if (talk.equals("quit")) {
                            disconnect();
                            bConnected = false;
                            break;
                        }
                        dos.writeUTF(talk);
                        dos.flush();
                    }
                    String talk = dis.readUTF();
                    System.out.println(talk);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
 

server端:

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.net.BindException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

public class ChatServer {
    boolean started = false;
    ServerSocket ss = null;
    
    List<Client> clients = new ArrayList<Client>();
    
    public static void main(String[] args) {
        new ChatServer().start();
    }
    
    public void start() {
        try {
            ss = new ServerSocket(8888);
            started = true;
        } catch (BindException e) {
            System.err.println("port in use.please stop program using this port and restart.");
            System.exit(0);
        } catch (IOException e) {
            e.printStackTrace();
        }
        
        try {
            while(started) {
                Socket s = ss.accept();
                Client c = new Client(s);
                // System.out.println("a client connected.");
                new Thread(c).start();
                clients.add(c);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                ss.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        
    }
    
    class Client implements Runnable {
        private Socket s;
        private DataInputStream dis = null;
        private DataOutputStream dos = null;
        private boolean bConnected = false;
        
        public Client(Socket s) {
            this.s = s;
            try {
                dis = new DataInputStream(s.getInputStream());
                dos = new DataOutputStream(s.getOutputStream());
                bConnected = true;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        
        public void send(String str) {
            try {
                dos.writeUTF(str);
                dos.flush();
            } catch (IOException e) {
                clients.remove(this);
                System.out.println("a client quit.");
                //e.printStackTrace();
            }
        }
        
        public void run() {
            try {
                while(bConnected) {
                    String str = dis.readUTF();
                    solveTalk(str);
                }    
            } catch (EOFException e) {
                System.out.println("Client closed!");
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if(dis != null) dis.close();
                    if(dos != null) dos.close();
                    if(s != null) {
                        s.close();
                        s = null;
                    }
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
        
        private void solveTalk(String talk) {
            System.out.println(talk);
            for(int i=0;i<clients.size();i++) {
                Client c = clients.get(i);
                c.send(talk);
            }
        }
    }
    
}