Socket聊天室 加强版

服务端代码

package com.xiva.demo.socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

public class SocketServer
{
    public final static List<Socket> socketList = new ArrayList<Socket>();
    
    public static int number = 0;
    
    public static void main(String[] args)
    {
        
        try
        {
            //绑定服务端在8888端口  
            ServerSocket server = new ServerSocket(8888);
            Socket socket;
            int count = 0;
            
            while (true)
            {
                
                //监听客户端程序  
                socket = server.accept();
                count = count + 1;
                
                System.out.println(socket.getInetAddress().getHostAddress());
                
                //一个客户端连接后启动一个线程进行监听客户端消息  
                ReadThread readThread = new ReadThread(socket);
                readThread.start();
                
                socketList.add(socket);
            }
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
}

class ThreadSocketServer extends Thread
{
    
    Socket server;
    
    public ThreadSocketServer()
    {
    }
    
    public ThreadSocketServer(Socket s)
    {
        this.server = s;
    }
    
    public void run()
    {
        try
        {
            
            BufferedReader br = new BufferedReader(new InputStreamReader(
                    System.in));
            PrintWriter pw = new PrintWriter(server.getOutputStream());
            
            //循环发送信息给客户端  
            while (true)
            {
                String s = br.readLine();
                pw.println(s);
                pw.flush();
                System.out.println("Server:" + s);
            }
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        
    }
    
}

class ReadThread extends Thread
{
    
    private Socket socket;
    
    public ReadThread(Socket socket)
    {
        this.socket = socket;
    }
    
    public void run()
    {
        try
        {
            BufferedReader br = new BufferedReader(new InputStreamReader(
                    socket.getInputStream()));
            String read = null;
            
//            ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
            
            StringBuffer sBuffer = new StringBuffer();
            //循环接受客户端信息  
            while (true)
            {
                read = br.readLine();
//                ois.readObject();
                
                if ("bye".equals(read))
                {
                    SocketServer.socketList.remove(this.socket);
                    break;
                }
                if(read.endsWith("#userName#"))
                {
                    String welcome = read.substring(0, read.length()-10);
                    List<Socket> socketList = SocketServer.socketList;
                    for (int i = 0; i < socketList.size(); i++)
                    {
                        Socket socket = socketList.get(i);
                        if (this.socket == socket)
                        {
                            continue;
                        }
                        PrintWriter pw = new PrintWriter(socket.getOutputStream());
                        
                        pw.println("Welcome " + welcome + " to join us talking!");
                        pw.flush();
                    }
                    continue;
                }
                
                sBuffer.append(read);
                if(!read.endsWith("#end#"))
                {
                    sBuffer.append("\r\n");
                    continue;
                }
                
                String userIp = socket.getInetAddress().getHostAddress();
                String content = sBuffer.substring(0, sBuffer.length() - 5);
                System.out.println(userIp + "client说:" + content);
                List<Socket> socketList = SocketServer.socketList;
                for (int i = 0; i < socketList.size(); i++)
                {
                    Socket socket = socketList.get(i);
                    if (this.socket == socket)
                    {
                        continue;
                    }
                    PrintWriter pw = new PrintWriter(socket.getOutputStream());
                    
                    pw.println(userIp + " say:\r\n" + content);
                    pw.flush();
                }
                
                sBuffer.delete(0, sBuffer.length());
                
            }
            br.close();
            socket.close();
            
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block  
            e.printStackTrace();
        }
    }
}

 

客户端代码:

package com.xiva.demo.socket;

import java.awt.Button;
import java.awt.Color;
import java.awt.Frame;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Label;
import java.awt.Panel;
import java.awt.TextArea;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.SocketException;

import javax.swing.JFrame;

/**
 * 
 * @author xiva
 *
 */
public class TalkFrame extends Frame implements ActionListener
{
    
    /**
     * serialVersionUID
     */
    private static final long serialVersionUID = 203806385437188889L;
    
    private TextArea msgSend;
    
    private TextArea msgShow;
    
    private TextArea onLineList;
    
    private Panel cPanel;
    
    private Panel cPanelMsg;
    
    private Label note1;
    
    private Button button_exe;
    
    private PrintWriter pWriter;
    
    private Socket socket;
    
    private ReadString read;
    
    public TalkFrame()
    {
        super("聊天室");
        JFrame msgFrame = new JFrame("聊天室");
        //        msgFrame.setLayout(new GridLayout(2, 2));
        cPanel = new Panel(new GridBagLayout());
        cPanelMsg = new Panel(new GridBagLayout());
        
        button_exe = new Button("发送消息");
        button_exe.setSize(80, 30);
        msgSend = new TextArea(10, 10);
        onLineList = new TextArea(27, 18);
        onLineList.setEditable(false);
        onLineList.setBackground(Color.WHITE);
        
        msgShow = new TextArea(27, 68);
        msgShow.setEditable(false);
        msgShow.setBackground(Color.WHITE);
        
        note1 = new Label("输入消息:");
        
        GridBagConstraints gbcon = new GridBagConstraints();
        
        // 设定第一个单元格的属性值  
        gbcon.gridx = 0;
        gbcon.gridy = 0;
        gbcon.gridwidth = 1;
        gbcon.gridheight = 1;
        gbcon.weightx = 0;
        gbcon.weighty = 0;
        gbcon.anchor = GridBagConstraints.WEST;
        gbcon.fill = GridBagConstraints.HORIZONTAL;
        gbcon.insets = new Insets(5, 5, 5, 5);
        gbcon.ipadx = 0;
        gbcon.ipady = 0;
        cPanelMsg.add(msgShow, gbcon);
        
        // 设定第二个单元格的属性值  
        gbcon.gridx = 1;
        gbcon.gridy = 0;
        gbcon.gridwidth = GridBagConstraints.REMAINDER;
        gbcon.gridheight = 1;
        gbcon.weightx = 1;
        gbcon.weighty = 0;
        gbcon.anchor = GridBagConstraints.EAST;
        gbcon.fill = GridBagConstraints.NONE;
        gbcon.insets = new Insets(0, 0, 0, 0);
        gbcon.ipadx = 0;
        gbcon.ipady = 0;
        cPanelMsg.add(onLineList, gbcon);
        
        GridBagConstraints gbc = new GridBagConstraints();
        
        // 设定第一个单元格的属性值  
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.gridwidth = 1;
        gbc.gridheight = 1;
        gbc.weightx = 0;
        gbc.weighty = 0;
        gbc.anchor = GridBagConstraints.NORTHWEST;
        gbc.fill = GridBagConstraints.NONE;
        gbc.insets = new Insets(0, 0, 0, 0);
        gbc.ipadx = 0;
        gbc.ipady = 0;
        cPanel.add(note1, gbc);
        
        // 设定第二个单元格的属性值  
        gbc.gridx = 1;
        gbc.gridy = 0;
        gbc.gridwidth = GridBagConstraints.REMAINDER;
        gbc.gridheight = 1;
        gbc.weightx = 1;
        gbc.weighty = 0;
        gbc.anchor = GridBagConstraints.CENTER;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.insets = new Insets(5, 5, 5, 5);
        gbc.ipadx = 0;
        gbc.ipady = 0;
        cPanel.add(msgSend, gbc);
        
        // 设定第二个单元格的属性值  
        gbc.gridx = 1;
        gbc.gridy = 1;
        gbc.gridwidth = GridBagConstraints.EAST;
        gbc.gridheight = 1;
        gbc.weightx = 1;
        gbc.weighty = 0;
        gbc.anchor = GridBagConstraints.EAST;
        gbc.fill = GridBagConstraints.NONE;
        gbc.insets = new Insets(1, 1, 1, 1);
        gbc.ipadx = 0;
        gbc.ipady = 0;
        cPanel.add(button_exe, gbc);
        
        msgFrame.addWindowListener(new WinClose());
        button_exe.addActionListener(this);
        msgFrame.getContentPane().add(cPanel, "South");
        msgFrame.getContentPane().add(cPanelMsg, "North");
        
        msgFrame.setSize(620, 680);
        msgFrame.setLocation(200, 200);
        msgFrame.setResizable(false);
        msgFrame.setVisible(true);
        
    }
    
    public TextArea getMsgShow()
    {
        return msgShow;
    }
    
    public void actionPerformed(ActionEvent e)
    {
        if (e.getSource() == button_exe)
        {
            if (pWriter == null)
            {
                String old = msgShow.getText();
                msgShow.setText(old + "\r\n" + "Server down!");
                msgSend.setText("");
            }
            else
            {
                String sendMsg = msgSend.getText();
                pWriter.println(sendMsg + "#end#");
                pWriter.flush();
                
                String old = msgShow.getText();
                msgShow.setText(old + "\r\nYou:\r\n" + sendMsg);
                msgSend.setText("");
            }
            
        }
    }
    
    public static void main(String arg[])
    {
        TalkFrame talk = new TalkFrame();
        talk.conent();
    }
    
    public void conent()
    {
        try
        {
            this.socket = new Socket("192.168.40.33", 8888);
            this.read = new ReadString(this);
            read.start();
            this.pWriter = new PrintWriter(this.socket.getOutputStream());
            
            this.pWriter.println(System.getProperty("user.name") + "#userName#");
            this.pWriter.flush();
        }
        catch (Exception e)
        {
            this.msgShow.setText("Connect Fail!");
        }
    }
    
    class WinClose implements WindowListener
    {
        
        @SuppressWarnings("deprecation")
        public void windowClosing(WindowEvent e)
        {
            try
            {
                if (socket != null)
                {
                    read.stop();
                    pWriter.println("bye");
                    pWriter.flush();
                    socket.close();
                }
            }
            catch (IOException ioe)
            {
                
            }
            finally
            {
                System.exit(0);
            }
            
        }
        
        public void windowOpened(WindowEvent e)
        {
        }
        
        public void windowActivated(WindowEvent e)
        {
        }
        
        public void windowDeactivated(WindowEvent e)
        {
        }
        
        public void windowClosed(WindowEvent e)
        {
        }
        
        public void windowIconified(WindowEvent e)
        {
        }
        
        public void windowDeiconified(WindowEvent e)
        {
        }
    }
    
    public Socket getSocket()
    {
        return socket;
    }
}

class ReadString extends Thread
{
    
    private Socket socket;
    
    private TextArea msgShow;
    
    public boolean exitProgram;
    
    public ReadString(Socket socket)
    {
        this.socket = socket;
    }
    
    public ReadString(TalkFrame talkFrame)
    {
        this.socket = talkFrame.getSocket();
        this.msgShow = talkFrame.getMsgShow();
    }
    
    public void run()
    {
        try
        {
            BufferedReader br = new BufferedReader(new InputStreamReader(
                    socket.getInputStream()));
            
            // 循环接受服务端信息  
            while (true)
            {
                String read = "";
                try
                {
                    read = br.readLine();
                }
                catch (SocketException se)
                {
                    System.out.println("Socket closed!");
                    if (socket.isClosed())
                    {
                        break;
                    }
                }
                
                System.out.println("Server:" + read);
                
                String old = msgShow.getText();
                msgShow.setText(old + "\r\n" + read);
                if (read.equals("bye"))
                {
                    break;
                }
            }
            br.close();
            socket.close();
            
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
}

 针对上一个版本多了Frame

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值