java socket编程--聊天小案例

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java socket编程--聊天小案例相关的知识,希望对你有一定的参考价值。

  很久以前写过socket聊天室,都快忘完了,心血来潮又重新写一遍。

服务器端:

技术分享
package com.fancy;

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.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

public class Server {
    private int port;
    private ServerSocket server;
    private Map<String,PrintWriter> clients = new HashMap();

    public Server() throws IOException {
        port = 10025;
        server = new ServerSocket(port);
        System.out.println("成功创建服务器端!");
        startReceive();
    }

    public void startReceive() throws IOException{
        while(true){
            Socket socket = server.accept();
            //InetAddress address = socket.getInetAddress();
            ClientHandler handler = new ClientHandler(socket);
            new Thread(handler).start();
        }
    }
    public void sendMsg(String from,String str) throws IOException {
        for(String k:clients.keySet()){
            if(k.equals(from)){
                continue;
            }
            PrintWriter pw = clients.get(k);
            pw.println(str);
            pw.flush();
        }
    }
    class ClientHandler implements Runnable{
        private String nickname;
        private Socket socket;
        private PrintWriter pw;
        public ClientHandler(Socket socket){
            this.socket = socket;
        }
        @Override
        public void run() {
            BufferedReader br = null;
            try {
                InputStream in = socket.getInputStream();
                br = new BufferedReader(new InputStreamReader(in));
                OutputStream out = socket.getOutputStream();
                pw = new PrintWriter(out,true);
                String name = br.readLine();
                this.nickname = name;
                if(!clients.containsKey(name)){
                    clients.put(name, pw);
                    pw.println("欢迎新朋友:"+name+",当前在线人数:"+clients.size());
                }
                String str;
                while((str = br.readLine())!=null){
                    if("exit".equalsIgnoreCase(str.trim())){
                        clients.remove(this.nickname);
                        this.socket.close();
                        sendMsg("all", this.nickname+"下线了,当前在线人数:"+clients.size());
                    }else{
                        sendMsg(name,name+":"+str);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally{
                try {
                    br.close();
                } catch (IOException e) {
                }
            }
        }
    }

    public static void main(String[] args) {
        try {
            Server s = new Server();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
View Code

客户端:

技术分享
package com.fancy;

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.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

public class Client {
    private Socket socket;
    private boolean online = true;
    public Client() throws UnknownHostException, IOException {
        socket = new Socket("127.0.0.1", 10025);
        OutputStream out = socket.getOutputStream();
        PrintWriter pw = new PrintWriter(out, true);
        Scanner scan = new Scanner(System.in);
        String word;
        ServerHandler hander = new ServerHandler();
        new Thread(hander).start();
        System.out.println("请输入您的昵称:");
        word = scan.nextLine();
        pw.println(word);
        pw.flush();
        while((word=scan.nextLine())!=null){
            pw.println(word);
            pw.flush();
            if("exit".equalsIgnoreCase(word)){
                online = false;
                break;
            }
        }
    }
    class ServerHandler implements Runnable{

        @Override
        public void run() {
            while(online){
                InputStream in;
                try {
                    in = socket.getInputStream();
                    BufferedReader br = new BufferedReader(new InputStreamReader(in));
                    String back = br.readLine();
                    System.out.println(back);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    public static void main(String[] args) {
        try {
            Client c = new Client();
            System.out.println("started!");
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        
    }
}
View Code

 

  运行一次server,多次client的结果如下:

  技术分享

 

以上是关于java socket编程--聊天小案例的主要内容,如果未能解决你的问题,请参考以下文章

网络编程用Socket实现聊天小程序

JAVA实战用socket通信编程制作多人聊天室

Java编程实例-tcp聊天室代码实现

基于java的socket简单聊天编程

微信小程序---Socket聊天功能实现

第94题JAVA高级技术-网络编程13(简易聊天室8:使用Socket传递图片)