Socket例子,仅引用

服务器端的源代码是:
/*
*
* @(#)Chat_Server.java
*
*
* @author
* @version 1.00 2009/4/2
*/

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Enumeration;
import java.util.Vector;

import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;


public class Chat_Server extends JPanel
{

private JPanel topPanel = new JPanel();
private JPanel buttonPanel = new JPanel();
private DefaultTableModel defaultModel;
private JTable nameTable;
private JButton exitButton;
private JList list;
private DefaultListModel listModel;
private JButton sendButton = new JButton("发送(S)");

private JTextField sayWord =new JTextField();

private Vector totalThread = new Vector();      //totalThread将所有连接保存在其中,当需要时从中取出
private int port = 8082;

    public Chat_Server()
    {
        this.setLayout(new GridLayout(2,1));
    }

    public void init()
    {
        String[]columName = new String[] {"用户名称","IP"
        };

        String[][] tempData = new String[][] {{"",""
    }};

defaultModel = new DefaultTableModel(tempData,columName);     //这一段....
nameTable =new JTable(defaultModel);
nameTable.setRowHeight(22);

exitButton =new JButton("关闭服务器(C)");
exitButton.addActionListener(new ActionListener(){          //
    public void actionPerformed(ActionEvent e){
        System.exit(0);
    }
});

topPanel.setLayout(new BorderLayout());
topPanel.add(new JLabel("在线用户",JLabel.LEFT),BorderLayout.NORTH);
topPanel.add(new JScrollPane(nameTable),BorderLayout.CENTER);

listModel = new DefaultListModel();
list = new JList(listModel);

JPanel temp =new JPanel(new BorderLayout());
temp.add(sayWord,BorderLayout.CENTER);
sendButton.addActionListener(new ActionListener(){         //按发送键 发送信息
    public void actionPerformed(ActionEvent arg0){
        sendData();
    }
});

sendButton.setMnemonic('s');                      //设置快捷键 ALT + S 发送  sendButton
//sendButton.setMnemonic(java.awt.event.KeyEvent.VK_ENTER);   //设置快捷键 CTRL + ENTER 发送  sendButton  不行
temp.add(sendButton,BorderLayout.EAST);
JPanel temp2 = new JPanel();
exitButton.setMnemonic('c');                //设置快捷键 ALT + C 关闭服务器 exitButton
temp2.add(exitButton);
temp.add(temp2,BorderLayout.SOUTH);

buttonPanel.setLayout(new BorderLayout());
buttonPanel.add(new JScrollPane(list),BorderLayout.CENTER);
buttonPanel.add(temp,BorderLayout.SOUTH);

this.add(topPanel);
this.add(buttonPanel);
new StartServer().start();
new UpdateThread().start();       //两进程

    }
class StartServer extends Thread
{
    public void run()
    {
        try
        {
            ServerSocket serverSocket = new ServerSocket(port);
            while(true)
            {
                try
                {
                    Socket s  = serverSocket.accept();
                    AcceptThread acceptThread = new AcceptThread(s);
                    acceptThread.start();
                    totalThread.add(acceptThread);
                }catch(IOException ex2)
                {
                    throw ex2;
                }
            }
        }catch(IOException e){
            e.printStackTrace();
        }
    }
}

private void addWord(String word)
{
    listModel.add(0,word);
}

private void sendData()       //sendData()用于将服务器发言发送给每一个客户端,具体发送由sendWordToEveryone完成
{
    String temp = "xinye说: "+sayWord.getText().trim();
    sendWordToEveryone(temp.getBytes());
    addWord(temp);
    sayWord.setText(""); //.....................................................重新设置为空.
}

class UpdateThread extends Thread
{
    public void run()
    {
        while(true)
        {
            String[] columName = new String[]{
                "用户名称","IP"
            };

            String[][] tempData = new String[][] {

            };

            defaultModel = new DefaultTableModel(tempData,columName);
            AcceptThread tempThread = null;
            Object tempObject = null;                              //这是什么 tempObject ?
            Enumeration enum1 = totalThread.elements();            //
            while(enum1.hasMoreElements())
            {
                tempObject = enum1.nextElement();
                if(tempObject !=null)
                {
                    tempThread = (AcceptThread)tempObject;
                    if(tempThread.isAlive())
                        defaultModel.addRow(new String[]{
                            tempThread.getUserName(),
                            tempThread.getUserIP()
                        });
                        else
                            tempObject= null;
                }

                nameTable.setModel(defaultModel);//创建了新的DefaultTableModel ,调用JTable的setModel方法后,JTable将显示
                                                 //这个DefaultTableModel的内容
            }

            try
            {
                sleep(6000);
            }catch(InterruptedException e){
                e.printStackTrace();
            }
        }
    }
}

public static void main(String[] args)
{
    JFrame mf = new JFrame("服务端");
    Chat_Server server = new Chat_Server();
    mf.getContentPane().add(server);
    mf.setLocation(150,0);
    mf.setSize(300,400);
    mf.setDefaultCloseOperation(mf.EXIT_ON_CLOSE);
    server.init();                           //
    mf.setVisible(true);
}

class AcceptThread extends Thread  //serverSocket为每一个客户请求都会生成一个新的AcceptThread线程
{
    Socket s = null;
    InputStream inputStream = null;
    OutputStream outputStream = null;
    String name= "此处为昵称";
    String ip;
    boolean flag = true;
    BufferedInputStream bis;
    BufferedOutputStream bos;
    byte[] bytes;

    public AcceptThread(Socket s)
    {
        this.s = s;
        ip = s.getInetAddress().getHostAddress();    //要获取客户端地址,这里应该写错了
        System.out.println(ip);

        try
        {
            inputStream = s.getInputStream();
            outputStream = s.getOutputStream();
            bos = new BufferedOutputStream(outputStream,1024);
        }catch(IOException e)
        {
            e.printStackTrace();
            if(s!=null)
            {
                try{
                    s.close();

                }catch(IOException e1){
                    e1.printStackTrace();
                }
            }
            flag = false;
        }
    }

    public void run()
    {
        bis = new BufferedInputStream(inputStream,1024);
        while(flag)
        {
            try
            {
                bytes = new byte[1024];
                bis.read(bytes);
                String tempS= new String(bytes);
                tempS = tempS.trim();
                name = tempS.substring(0,tempS.indexOf("说"));           //subString or substring
                addWord(tempS);                                          //查 addWord
                sendWordToEveryone(bytes);
            }catch(IOException e)
            {
                e.printStackTrace();
                flag = false;
            }
        }
    }

    public void sendWord(byte[] bytes)          //AcceptThread用sendWord来向和自己建立专线连接的客户发送数据
    {
        try
        {
            bos.write(bytes);
            bos.flush();
        }catch(IOException e){
            e.printStackTrace();
        }
    }

    public String getUserName()         //用于返回当前客户端的名称
    {
        return name;
    }

    public String getUserIP()
    {
        return ip;
    }
}

private void sendWordToEveryone(byte[] bytes)    //sendwordToEveryone从totalThread中提取每一个AcceptThead并向活动的线程发送数据
{
Enumeration enum1 = totalThread.elements();
while(enum1.hasMoreElements())
{
    Object tempObject = enum1.nextElement();
    if(tempObject != null)
    {
        AcceptThread tempThread = (AcceptThread)tempObject;
        if(tempThread.isAlive())
        {
            tempThread.sendWord(bytes);
        }
    }
}
}
}


客户端的代码是:
/**
* @(#)Chat_Client.java
*
*
* @author
* @version 1.00 2009/4/1
*/

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent; 
import java.awt.*;
import java.awt.event.*;               
                                 //以上界面相关

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;     //以上通信相关

import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;

import java.lang.InterruptedException;        //
public class Chat_Client extends JPanel{

private InputStream inputStream;
private OutputStream outputStream;
private JTextField sayText = new JTextField();
private Socket s;                            
private DefaultListModel listModel = new DefaultListModel();       //DefaultListModel vs JList
private JList list = new JList(listModel);
private JTextField nameText = new JTextField(10);
private BufferedOutputStream bos;
private JButton sendButton = new JButton("发送(S)");

private String host ="";
private JTextField  hostIP = new JTextField(15);
private int port = 8082;

public void init()
{
    nameText.setText("此处昵称");
    setLayout(new BorderLayout());
    add(this.getContextPane(),BorderLayout.CENTER);
    add(this.getButtonPanel(),BorderLayout.SOUTH);   


    //this.startClient(host,port);
}

public static void main(String[] args)
{
    JFrame frame = new JFrame("客户端");
    frame.setSize(300,400);
    frame.setLocation(150,100);
    Chat_Client chatClient = new Chat_Client();
    chatClient.init();
    frame.getContentPane().add(chatClient);

    frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
    frame.setVisible(true);
}

private boolean flag = true;

//startClient与服务器建立连接并获取输入输出流
private void startClient(String host,int port)
{
    try
    {  
        host = hostIP.getText();
        s  = new Socket(InetAddress.getByName(host),port);
        inputStream = s.getInputStream();
        outputStream = s.getOutputStream();
        bos = new BufferedOutputStream(outputStream,1024);
        System.out.println(bos);
        new ResevWord(inputStream).start();
    }catch(UnknownHostException e)
    {
        e.printStackTrace();

    }catch(IOException e)
    {
        e.printStackTrace();
            flag = false;
    }
}

//sendData将数据发往服务器
private void sendData()
{
    String word = nameText.getText()+"说: "+sayText.getText();
    try
    {
        bos.write(word.getBytes());
        bos.flush();
    }catch(IOException e)
    {
        e.printStackTrace();
    }
    sayText.setText("");        //重新设为空
}


class ResevWord extends Thread           //ReseWord可用于创建新的线程,用于接收数据
{
InputStream ips = null;
BufferedInputStream bis =null;
byte[] bytes = new byte[1024];
public ResevWord(InputStream ips)
{
    this.ips = ips;
    bis = new BufferedInputStream(ips,1024);
}

public void run()
{
    while(flag)                                       //循环,多个客户端?
    {
        try{

            try{
                bis.read(bytes);
                String word =new String(bytes);
                word = word.trim();
                listModel.add(0,word);      //在此列表的指定位置处插入指定元素
            }catch(IOException ex){
                ex.printStackTrace();
                flag = false;
            }
        }catch(Exception ee){
            ee.printStackTrace();
        }
    }
}
}

private JPanel getContextPane()
{
    JPanel panel = new JPanel();
    panel.setLayout(new BorderLayout());
    JPanel p1 = new JPanel();
    p1.setLayout(new BorderLayout());

    JPanel p11 = new JPanel();
    //p11.setLayout(new BorderLayout());
    JLabel j1 = new JLabel("我是");
    p11.add(j1);
    p11.add(nameText);

    JPanel p12 = new JPanel();
    JLabel j2 = new JLabel("服务器IP");
    p12.add(j2);
    p12.add(hostIP);
   
    JPanel p13 = new JPanel();
    JButton connectServer = new JButton("连接服务器");
   connectServer.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e){
            startClient(host,8082);
        }
    });
   
     p13.add(connectServer);
  
    p1.add(p11,BorderLayout.NORTH);
    p1.add(p12,BorderLayout.CENTER);
    p1.add(p13,BorderLayout.SOUTH);
      
        panel.add(p1,BorderLayout.NORTH);
    panel.add(new JScrollPane(list),BorderLayout.CENTER);           //有个list
    return panel;
}

private JPanel getButtonPanel()
{
    JPanel panel = new JPanel();
    panel.setLayout(new BorderLayout());
    panel.add(sayText,BorderLayout.CENTER);
    sendButton.setMnemonic('s');                        //快捷键  ALT + S  sendButton 发送
     sendButton.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e){
            sendData();
        }
    });
    panel.add(sendButton,BorderLayout.EAST);
    return panel;
}

}

本文代码来自:http://topic.csdn.net/u/20090404/01/2f349eb7-26b5-49ae-8955-78cc74bfd545.html

你可能感兴趣的:(java,thread,.net,socket,swing)