Client.java
package SocketCode;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.net.*;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Client extends JFrame implements ActionListener
{
JTextArea Show = null;
JTextField Send = null;
JButton Click1 = null;
JButton Click2=null;
JPanel panel= null;
JScrollPane Roll = null;
JFrame T=null;
PrintWriter NET =null;
JLabel label=null;
public static void main(String [] args)
{
Client client= new Client();
client.Client1();
}
public void Client1(){
panel= new JPanel(new GridLayout(1,1));
label=new JLabel();
this.add(label,"West");
Show = new JTextArea();
Send = new JTextField(20);
Click1= new JButton("点我发送");
Click1.setBounds(40, 200, 200, 200);
Click1.setBackground(Color.white);
Click1.addActionListener((ActionListener) this);
Click2=new JButton( "点我关闭");
Click2.setBounds(40, 200, 200, 200);
Click2.setBackground(Color.red);
Click2.addActionListener((ActionListener) this);
JScrollPane Roll = new JScrollPane(Show);
JFrame.setDefaultLookAndFeelDecorated(true);
Show.setForeground(Color.blue);
Show.setLineWrap(true);
panel.add(Send);
panel.add(Click1);
panel.add(Click2);
Font font = new Font("Serief", Font.ITALIC + Font.BOLD, 28);// 设置字体
label.setFont(font);// 设置标签字体
label.setText("相见恨晚聊天室 ");
this.add(Roll,"Center");
this.add(panel,"South");
this.setTitle("我是收到客户端");
this.setSize(800,600);
this.setLocation(400,200);
this.setVisible(true);
try {
InetAddress host = InetAddress.getLocalHost();
String ip =host.getHostAddress();
Socket s = new Socket(ip,14800);
if(s!=null){
this.setVisible(true);
}
InputStream is=s.getInputStream();
InputStreamReader in=new InputStreamReader(is);
BufferedReader br = new BufferedReader(in);
NET = new PrintWriter(s.getOutputStream(),true);
while(true){
Date date=new Date();
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String time=sdf.format(date);
String information = br.readLine();
Show.append("发起者说:"+information+"\r\n"+"time:"+time+"\r\n");
if(s!=null){
this.setVisible(true);
}
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void actionPerformed (ActionEvent e) {
if(e.getSource()==Click1 ){
Date date=new Date();
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String time=sdf.format(date);
panel.setBackground(Color.LIGHT_GRAY);
String information = Send.getText();
Show.append("收到者:"+information+"\r\n"+"time:"+time+"\r\n");
NET.println(information);
Send.setText("");
}else
{
if(e.getSource()==Click2){
this.setVisible(false);
}
}
}
}
Server.java
package SocketCode;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.net.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.*;
public class Server extends JFrame implements ActionListener{
JTextArea Show = null;
JTextField Send = null;
JButton Click1 = null;
JButton Click2=null;
JPanel Panel= null;
JScrollPane Roll = null;
PrintWriter character =null;
JLabel label=null;
public static void main(String [] args){
Server trist= new Server();
trist.ServerList();
}
public void ServerList(){
label=new JLabel(" 你要知道你配的上世间的所有美好 ! ");
this.add(label,"West");
Show = new JTextArea();
Send = new JTextField(20);
Click1= new JButton("点我发送");
Click1.setBounds(40, 200, 200, 200);
Click1.setBackground(Color.white);
Click1.addActionListener(this);
Click2= new JButton("点我关闭");
Click2.setBounds(40, 200, 200, 200);
Click2.setBackground(Color.red);
Click2.addActionListener(this);
Panel = new JPanel();
Roll = new JScrollPane(Show);
Panel.add(Send);
Panel.add(Click1);
Panel.add(Click2);
this.add(Roll);
this.add(Panel,"South");
this.setTitle("1号发起者");
this.setSize(500,400);
this.setBounds(400, 400, 800, 600);
this.setVisible(true);
Show.setForeground(Color.red);
Show.setLineWrap(true);//自动换行
try {
ServerSocket TT= new ServerSocket(14800);
Socket s = TT.accept();
if(s!=null){
this.setVisible(true);
}
InputStream is=s.getInputStream();
InputStreamReader isr=new InputStreamReader(is);
BufferedReader brd = new BufferedReader(isr);
character = new PrintWriter(s.getOutputStream(),true);
while(true){
Date date=new Date();
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String time=sdf.format(date);
String message = brd.readLine();
Show.append("收到者说:"+message+"\r\n"+"time:"+time+"\r\n");
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void actionPerformed(ActionEvent e) {
if(e.getSource()==Click1){
Date date=new Date();
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String time=sdf.format(date);
String message = Send.getText();
Show.append("发起者:"+message+"\r\n"+"time:"+time+"\r\n");
character.println(message);
Send.setText("");
}else{
if(e.getSource()==Click2){
this.setVisible(false);
}
}
}
}
connection.java
package demo_test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.StringTokenizer;
import java.util.Vector;
public class connection {
static int port = 5566;
static Vector<Client> clients = new Vector<Client>(10);
static ServerSocket server = null;
static Socket socket = null;
public connection() {
try {
System.out.println("服务启动");
server = new ServerSocket(port);
while (true) {
socket = server.accept();
System.out.println(socket.getInetAddress()+"连接\n");
Client client = new Client(socket);
clients.add(client);
client.start();
notifyChatRoom();
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static void notifyChatRoom()
{
StringBuffer newUser = new StringBuffer("用户");
for (int i = 0; i < clients.size(); i++)
{
Client c = (Client)clients.elementAt(i);
newUser.append(":"+c.name);
}
sendClients(newUser);
}
public static void sendClients(StringBuffer message)
{
for (int i= 0 ; i < clients.size(); i++)
{
Client client = (Client)clients.elementAt(i);
client.send(message);
}
}
public void closeAll()
{
while (clients.size() > 0 )
{
Client client = (Client) clients.firstElement();
try {client.socket.close();
} catch(IOException ex)
{
ex.printStackTrace();
}
clients.removeElement(client);
}
}
public static void disconnect(Client c)
{
try {System.err.println(c.ip+"断开连接\n");
} catch (Exception ex)
{
ex.printStackTrace();}
clients.removeElement(c);
c.socket = null;}
public static void main(String[] args)
{
new connection();
}
class Client extends Thread
{
Socket socket;
String name ;
String ip;
BufferedReader reader;
PrintStream ps;
public Client(Socket s)
{
socket = s;
try {
reader = new BufferedReader(new InputStreamReader(s.getInputStream()));
ps = new PrintStream(s.getOutputStream());
String info = reader.readLine();
StringTokenizer stinfo = new StringTokenizer(info,":");
String head = stinfo.nextToken();
System.out.println(stinfo.toString());
System.out.println(head);
if (stinfo.hasMoreTokens())
{
name = stinfo.nextToken() ;
}
if (stinfo.hasMoreTokens()) {
ip = stinfo.nextToken();
}
} catch (IOException ex)
{
ex.printStackTrace();}
System.out.println(name);
System.out.println(ip);
}
public void send (StringBuffer msg)
{
ps.println(msg);
ps.flush();
}
public void run()
{
while (true)
{
String line = null;
try {
line = reader.readLine();
System.out.println("line:"+line);
} catch (IOException ex) {
ex.printStackTrace();
connection.disconnect(this);
connection.notifyChatRoom();
return ;
}
if (line == null)
{
connection.disconnect(this);
connection.notifyChatRoom();
return ;
}
StringTokenizer st = new StringTokenizer(line,":");
String keyword = st.nextToken();
if (keyword.equals("MSG"))
{
StringBuffer msg = new StringBuffer("MSG:");
msg.append(name);
msg.append(st.nextToken("\0\n"));
connection.sendClients(msg);
System.out.println(msg);
} else if (keyword.equals("quit"))
{
connection.disconnect(this);
connection.notifyChatRoom();
}
}
}
}
}
gogogo.java
package demo_test;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.InetAddress;
import java.net.Socket;
import java.util.StringTokenizer;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class gogogo extends JFrame implements ActionListener ,Runnable{
TextField tfName = new TextField(15);
Button btConnect = new Button("连接");
Button btDisconnect = new Button("断开连接");
TextArea tfChat = new TextArea(8,30);
Button btSend = new Button("发送");
TextField tfMessage = new TextField(50);
java.awt.List list1 = new java.awt.List(9);
Socket socket = null;
PrintStream ps = null;
Listen listen = null;
class Listen extends Thread
{
BufferedReader reader;
PrintStream ps;
String cname;
Socket socket;
gogogo chatClient;
public Listen(gogogo client,String name,Socket socket)
{
try {this.chatClient = client;
this.socket = socket;
this.cname = name;
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
ps = new PrintStream(socket.getOutputStream());
} catch (IOException e) {
e.printStackTrace();}
}
public void run()
{
while (true)
{
String line=null ;
try {
line = reader.readLine();
System.out.println("客户端:"+line);}catch (IOException ex)
{
ex.printStackTrace();
ps.println("quit");
return;
}
StringTokenizer stinfo = new StringTokenizer(line,":");
String keyword = stinfo.nextToken();
if (keyword.equals("MSG"))
{
chatClient.tfChat.append(line+"\n");
}
else if (keyword.equals("用户"))
{
chatClient.list1.clear();
chatClient.list1.add("users", 0);
int i = 1;
while (stinfo.hasMoreTokens())
{
chatClient.list1.add(stinfo.nextToken(), i++);
}
}
}
}
}
public void actionPerformed(ActionEvent e)
{
try{if(e.getSource()==btConnect)
{
if (socket == null)
{
socket = new Socket(InetAddress.getLocalHost(),5566);
ps = new PrintStream(socket.getOutputStream());
StringBuffer info = new StringBuffer("info:");
String userinfo = tfName.getText()+":"+InetAddress.getLocalHost().toString();
ps.println(info.append(userinfo));
ps.flush();
listen = new Listen(this,tfName.getText(),socket);
listen.start();}
} else if (e.getSource() == btDisconnect)
{
disconnect();
} else if (e.getSource() == btSend)
{
if (socket != null) {
StringBuffer msg = new StringBuffer("MSG:");
String sup = new String(tfMessage.getText());
ps.println(msg.append(sup));
ps.flush();
} else {
JOptionPane.showMessageDialog(this, "您还未链接,请先连接!", "提示", 1);
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
public void disconnect()
{
if (socket != null)
{
ps.println("quit");
ps.flush();
socket = null;
tfName.setText("");
}
}
public gogogo(Socket socket)
{
this.setLayout(new BorderLayout());
JPanel panel1 = new JPanel();
Label label = new Label("姓名");
panel1.setBackground(Color.gray);
panel1.add(label);
panel1.add(tfName);
panel1.add(btConnect);
panel1.add(btDisconnect);
this.add(panel1,BorderLayout.NORTH);
JPanel panel2 = new JPanel();
panel2.add(tfChat);
panel2.add(list1);
this.add(panel2,BorderLayout.CENTER);
JPanel panel3 = new JPanel();
Label label2 = new Label("聊天信息");
panel3.add(label2);
panel3.add(tfMessage);
panel3.add(btSend);
this.add(panel3,BorderLayout.SOUTH);
this.setBounds(750,350,500,350);
this.setVisible(true);
btConnect.addActionListener(this);
btDisconnect.addActionListener(this);
btSend.addActionListener(this);
pack(); }
public static void main(String[] args)
{
gogogo client = new gogogo(new Socket());
System.out.println(client.socket);
}
@Override
public void run()
{
// TODO 自动生成的方法存根
}
}
效果图:
ClientChat.java
import java.awt.BorderLayout;
import java.awt.HeadlessException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class ClientChat extends JFrame{
private JTextArea ta=new JTextArea(10,20);
private JTextField tf=new JTextField(20);
private static final String CONNSTR="127.0.0.1";
private static final int CONNPORT=888;
private Socket s=null;
private DataOutputStream dos=null;
private boolean isConn=false;
public ClientChat() throws HeadlessException {
super();
// TODO Auto-generated constructor stub
}
public void init() {
this.setTitle("客户端窗口");
this.add(ta,BorderLayout.CENTER);
this.add(tf,BorderLayout.SOUTH);
this.setBounds(300,300,300,400);
tf.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String strSend=tf.getText();
//strSend发送到服务器上
send(strSend);
if(strSend.trim().length()==0) {
return;
}
tf.setText("");
//ta.append(strSend+"\n");
}
});
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ta.setEditable(false);
tf.requestFocus();//光标聚焦
try {
s=new Socket(CONNSTR,CONNPORT);
//连上服务器
isConn=true;
} catch (UnknownHostException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
this.setVisible(true);
new Thread(new Receive()).start();//启动多线程
}
//发送信息到服务器的方法
public void send(String str) {
try {
dos=new DataOutputStream(s.getOutputStream());
dos.writeUTF(str);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//多线程的类,实现了runnable借口的
class Receive implements Runnable{
public void run() {
try {
while(isConn) {
DataInputStream dis =new DataInputStream(s.getInputStream());
String str=dis.readUTF();
ta.append(str);
}
} catch(SocketException e) {
System.out.println("服务器意外终止\n");
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void main(String[] args) {
ClientChat cc =new ClientChat();
cc.init();
}
}
ServerChat.java
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.event.WindowListener;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Iterator;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class ServerChat extends JFrame{
private static final int PORT=888;
JTextArea serverTa=new JTextArea();
private JPanel btnTool=new JPanel();
private JButton startBtn=new JButton("启动");
private JButton stopBtn =new JButton("停止");
private ServerSocket ss=null;
private ArrayList<ClientConn> ccList=new ArrayList<ClientConn>();
private boolean isStart=false;
public ServerChat(){
this.setTitle("服务器端");
this.add(serverTa,BorderLayout.CENTER);
btnTool.add(startBtn);
btnTool.add(stopBtn);
this.add(btnTool,BorderLayout.SOUTH);
this.setBounds(0,0,500,500);
if(isStart) {
serverTa.append("服务器已经启动\\n");
}else {
serverTa.append("服务器还没有启动,请点击启动按钮\\n\\n");
}
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
isStart=false;
try {
if(ss!=null) {
ss.close();
}
System.out.println("服务器停止");
serverTa.append("服务器断开\n");
System.exit(0);
}catch (IOException e1) {
e1.printStackTrace();
}
}
});
stopBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
isStart=false;
try {
if(ss!=null) {
ss.close();
isStart=false;
}
System.exit(0);
serverTa.append("服务器断开\n");
System.out.println("服务器停止");
}catch (IOException e1) {
e1.printStackTrace();
}
}
});
startBtn.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
try {
if(ss==null) {
ss=new ServerSocket(PORT);
}
isStart=true;
serverTa.append("服务器已经启动"+"\n");
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
//服务器窗口关闭应该停止服务器
//serverTa.setEditable(false);
this.setVisible(true);
startServer();
}
//服务器启动的方法
public void startServer() {
try {
try {
ss=new ServerSocket(PORT);
isStart=true;
}catch(IOException e2) {
e2.printStackTrace();
}
while (isStart) {
Socket s = ss.accept();
ccList.add(new ClientConn(s));
System.out.println("一个客户端连接服务器:" + s.getInetAddress() + "/" + s.getPort());
serverTa.append("一个客户端连接服务器:" + s.getInetAddress() + "/" + s.getPort()+"\n");
}
//reciveStr();
}catch(SocketException e) {
System.out.println("服务器中断了");
//e.printStackTrace();
}catch(IOException e) {
e.printStackTrace();
}
}
//服务器停止的方法
//服务器接收数据的方法多线程的接收
/*public void reciveStr() {
try {
dis=new DataInputStream(s.getInputStream());
String str=dis.readUTF();
System.out.println(str);
serverTa.append(str);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}*/
//这个对象是属于服务器端的一个连接对象
class ClientConn implements Runnable{
Socket s=null;
public ClientConn(Socket s) {
this.s=s;
(new Thread(this)).start();
}
//同时接受客户端信息的多线程接受数据
public void run() {
try {
DataInputStream dis=new DataInputStream(s.getInputStream());
while(isStart) {
String str=dis.readUTF();
System.out.println(s.getInetAddress()+"|"+s.getPort()+"说:"+str+"\n");
serverTa.append(s.getInetAddress()+"|"+s.getPort()+"说:"+str+"\n");
String strSend=s.getInetAddress()+"|"+s.getPort()+"说:"+str+"\n";
Iterator<ClientConn> it= ccList.iterator();
while(it.hasNext()) {
ClientConn o=it.next();
o.send(strSend);
}
}
}catch(SocketException e) {
System.out.println("一个客户端下线了");
serverTa.append(s.getInetAddress()+"|"+s.getPort()+"客户端下线");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//每个连接对象发送数据的方法
public void send(String str){
try {
DataOutputStream dos=new DataOutputStream(this.s.getOutputStream());
dos.writeUTF(str);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void main(String[] args) {
ServerChat sc=new ServerChat();
}
}
Client.java
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
public class Client {
Socket socket;
BufferedWriter bw;
BufferedReader br;
public Client(String ip, int port) {
try {
socket = new Socket(ip,port);
bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void sendMessage(String message) {//发消息
try {
bw.write(message);//输出流
bw.newLine();//换行
bw.flush();//刷新
} catch (IOException e) {
e.printStackTrace();
}
}
public String reciveMessage() {//收消息
String message = null;
try {
message = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return message;
}
public void close() {
try {
socket.close();
} catch(SocketException e) {
System.out.println("一个客户端下线了");
}catch (IOException e) {
e.printStackTrace();
}
}
}
ClientFrame.java
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.util.Date;
import java.text.SimpleDateFormat;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import com.sun.glass.events.WindowEvent;
public class ClientFrame extends JFrame {
private JPanel contentPane;
private JLabel lblUserName;//显示用户名
private JTextField tfMessage;//信息发送文本框
private JButton btnSend;//发送按钮
private JTextArea textArea;//信息接收文本域
private String userName;//用户名称
Client client;
/**
* 客户端窗体的构造方法
*
* @param ip
* 服务器IP地址
* @param userName
* 用户名
*/
public ClientFrame(String ip,String userName) {
this.userName = userName;
init();//添加窗口初始化内容
addListener();// 添加监听
client = new Client(ip, 4567);
ReadMessageThread t = new ReadMessageThread();
t.start();
}
private class ReadMessageThread extends Thread{
public void run() {
while(true) {
String str = client.reciveMessage();//获取信息
textArea.append(str+"\n");
}
}
}
private void init() {
setTitle("客户端");
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(null);
setContentPane(contentPane);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(5, 5, 434, 229);
contentPane.add(scrollPane);
textArea = new JTextArea();
scrollPane.setViewportView(textArea);
textArea.setEditable(false);
JPanel panel = new JPanel();
panel.setBounds(5, 235, 434, 32);
contentPane.add(panel);
panel.setLayout(null);
lblUserName = new JLabel(userName);
lblUserName.setHorizontalAlignment(SwingConstants.TRAILING);
lblUserName.setBounds(2, 4, 55, 22);
panel.add(lblUserName);
tfMessage = new JTextField();
tfMessage.setBounds(62, 5, 274, 22);
tfMessage.setColumns(10);
panel.add(tfMessage);
btnSend = new JButton("发送");
btnSend.setBounds(336, 4, 93, 23);
panel.add(btnSend);
tfMessage.validate();
}
private void addListener() {
btnSend.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Date date = new Date();
SimpleDateFormat sf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
client.sendMessage(userName+" "+sf.format(date)+":\n"+tfMessage.getText());
tfMessage.setText("");//文本框清空
}
});
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent atg0) {
int op = JOptionPane.showConfirmDialog(ClientFrame.this,"确定要退出聊天室吗?","确定",JOptionPane.YES_NO_CANCEL_OPTION);
if (op == JOptionPane.YES_OPTION) {
client.sendMessage("%EXIT%:"+userName);
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
client.close();
System.exit(0);//关闭程序
}
}
});
}
}
LinkServerFarm.java
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
/**
* 连接服务器窗体
*/
public class LinkServerFarm extends JFrame{
private JPanel contentPane;
private JLabel lblIP;
private JLabel lblUserName;
private JTextField tfIP;//信息发送文本框
private JTextField tfUserName;
private JButton btnLink;//发送按钮
/**
* 连接服务器窗体的构造方法
* @return
* @return
*/
public LinkServerFarm() {
setTitle("连接服务器");
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 390, 150);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(null);
setContentPane(contentPane);
lblIP = new JLabel("服务器IP地址:");
lblIP.setFont(new Font("微软雅黑",Font.PLAIN, 14));
lblIP.setBounds(20, 15, 100, 15);
contentPane.add(lblIP);
tfIP = new JTextField("127.0.0.1");
tfIP.setBounds(121, 13, 242, 21);
contentPane.add(tfIP);
tfIP.setColumns(10);
lblUserName = new JLabel("用户名:");
lblUserName.setFont(new Font("微软雅黑", Font.PLAIN, 14));
lblUserName.setBounds(60, 40, 60, 15);
contentPane.add(lblUserName);
tfUserName = new JTextField();
tfUserName.setBounds(121, 42, 242, 21);
contentPane.add(tfUserName);
tfUserName.setColumns(10);
btnLink = new JButton("连接服务器");
btnLink.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
do_btnLink_actionPerformed(e);
}
});
btnLink.setFont(new Font("微软雅黑", Font.PLAIN, 14));
btnLink.setBounds(140, 80, 120, 23);
contentPane.add(btnLink);
}
protected void do_btnLink_actionPerformed(ActionEvent e) {
if(!tfIP.getText().equals("") && !tfUserName.getText().equals("")) {//文本框里的内容不能为空!
dispose();
ClientFrame clientFrame = new ClientFrame(tfIP.getText().trim(),tfUserName.getText().trim());
clientFrame.setVisible(true);//显示客户端窗口
}else {
JOptionPane.showMessageDialog(null, "文本框里的内容不能为空!", "警告", JOptionPane.WARNING_MESSAGE);
}
}
public static void main(String[] args) {
LinkServerFarm linkServerFrame = new LinkServerFarm();// 创建连接服务器窗体对象
linkServerFrame.setVisible(true);// 显示连接服务器窗体
}
}
Server.java
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashSet;
public class Server {
private HashSet<Socket> allSocket;
private ServerSocket server;
public Server() {
try {
server = new ServerSocket(4567);
System.out.println("服务器已连接!\n");
} catch (IOException e) {
e.printStackTrace();
}
allSocket = new HashSet<>();
}
public void startServer() throws IOException {
while(true) {
Socket socket = server.accept();
System.out.println("用户进入聊天室");
allSocket.add(socket);
ServerThread t = new ServerThread(socket);
t.start();
}
}
public class ServerThread extends Thread{
Socket socket;
public ServerThread(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while(true) {
String str = br.readLine();
if(str.contains("EXIT")) {// “%EXIT%:用户名”
String tmp = str.split(":")[1]+"用户退出聊天室";
sendMessageToAllClinet(tmp);
allSocket.remove(socket);
socket.close();
return;
}
sendMessageToAllClinet(str);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void sendMessageToAllClinet(String str) {
for(Socket s:allSocket) {
try {
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
bw.write(str);
bw.newLine();
bw.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
Server s = new Server();
try {
s.startServer();
} catch (IOException e) {
e.printStackTrace();
}
}
}
server.java
package last;
import java.awt.Color;
import java.awt.Container;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.WindowConstants;
import javax.swing.border.EmptyBorder;
public class server extends JFrame implements ActionListener{
private JButton start,stop,s;
private JTextField textField,textxiaoxi;
private JTextArea textMessage = new JTextArea();
private DataInputStream inputFromClient ;
private DataOutputStream outputToClient ;
private JPanel contentPane;
ServerSocket serverSocket;
Socket socket;
public static void main(String[] args) {
// TODO 自动生成的方法存根
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
server frame = new server();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public server() {
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JPanel panel = new JPanel();
panel.setBounds(0, 0, 426, 57);
contentPane.add(panel);
panel.setLayout(null);
JLabel label = new JLabel("端口:");
label.setBounds(12, 12, 39, 15);
panel.add(label);
textField = new JTextField();
textField.setText("8888");
textField.setBounds(55, 10, 50, 19);
panel.add(textField);
textField.setColumns(10);
JPanel panel_1 = new JPanel();
panel_1.setBounds(0, 69, 416, 170);
contentPane.add(panel_1);
JPanel panel_2 = new JPanel();
panel_2.setBounds(10, 240, 428, 89);
contentPane.add(panel_2);
panel_2.setLayout(null);
textMessage = new JTextArea();
textMessage.setTabSize(4);
textMessage.setRows(11);
textMessage.setColumns(35);
textMessage.setBackground(Color.LIGHT_GRAY);
textMessage.setText("欢迎进入server平台");
panel_1.add(textMessage);
textxiaoxi = new JTextField();
textxiaoxi.addActionListener(new sendListener());
//txtXiaoxi.setText("xiaoxi");
textxiaoxi.setBounds(20, 245, 300, 25);
contentPane.add(textxiaoxi);
textxiaoxi.setColumns(10);
start = new JButton("连接");
start.setBounds(200, 7, 70, 25);
panel.add(start);
start.addActionListener(this);
JButton button_2 = new JButton("发送");
button_2.setBounds(324, 5, 70, 25);
panel_2.add(button_2);
button_2.addActionListener(new sendListener());
stop = new JButton("断开");
stop.addActionListener(this);
stop.setBounds(300, 7, 70, 25);
panel.add(stop);
this.setSize(600, 420);
this.setLocation(600, 300);
this.add(panel_1);
this.add(panel_2);
this.setTitle("server界面");
this.setVisible(true);
}
private class sendListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
try {
outputToClient.writeUTF(textxiaoxi.getText().trim() + '\n'); //向服务器发送消息
textMessage.append("发送的消息:" + textxiaoxi.getText().trim() +'\n');
textxiaoxi.setText(""); //输出后清空输入框
} catch (IOException e1) {
System.err.println(e1);
}
}
}
private class Server_thread implements Runnable{
public Server_thread(){
}
public void run(){
try {
//IO流
inputFromClient = new DataInputStream(socket.getInputStream());
outputToClient = new DataOutputStream(socket.getOutputStream());
//获取客户端的名称 和 IP
InetAddress inetAddress = socket.getInetAddress();
String clientName = inetAddress.getHostName();
String clientIP = inetAddress.getHostAddress();
while(true){
String fromClient = inputFromClient.readUTF();
textMessage.append("客户端" + clientName + "; " + clientIP + "发来消息: "+fromClient);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO 自动生成的方法存根
if(e.getSource()==start) {
int port = Integer.parseInt(textField.getText());
try {
serverSocket = new ServerSocket(port);
textMessage.append("服务器已启动~~ 启动时间:" + new Date() +'\n');
//监听连接请求
socket = serverSocket.accept();
textMessage.append("连接成功~~~" + '\n');
Server_thread server3_thread = new Server_thread();
Thread thread = new Thread(server3_thread);
thread.start();
} catch (IOException e1) {
System.out.println(e1);
}
}
if(e.getSource()==stop) {
try {
inputFromClient.close();
outputToClient.close();
socket.close();
textMessage.append("连接已断开~~~");
} catch (Exception e2) {
// TODO: handle exception
}
}
}
}
Client.java
package last;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.Container;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
import javax.swing.WindowConstants;
public class Client extends JFrame implements ActionListener{
private JPanel contentPane;
private JTextField textField_IP;
private JTextField textField_Port;
private JTextField txtXiaoxi;
//IO流
private DataOutputStream toServer;
private DataInputStream fromServer;
JTextArea txtMessage;
Socket socket;
public Client() { //gui
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setToolTipText("Client");
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JPanel panel = new JPanel();
panel.setBounds(12, 5, 415, 100);
contentPane.add(panel);
panel.setLayout(null);
JLabel lblip = new JLabel("服务器IP:");
lblip.setBounds(12, 12, 65, 15);
panel.add(lblip);
textField_IP = new JTextField();
textField_IP.setText("localhost");
textField_IP.setBounds(82, 10, 114, 19);
panel.add(textField_IP);
textField_IP.setColumns(10);
JLabel label = new JLabel("端口:");
label.setBounds(214, 12, 49, 15);
panel.add(label);
textField_Port = new JTextField();
textField_Port.setText("8888");
textField_Port.setBounds(265, 10, 114, 19);
panel.add(textField_Port);
textField_Port.setColumns(10);
JButton button = new JButton("连接");
button.setBounds(80, 50, 80, 20);
panel.add(button);
JButton button_1 = new JButton("断开");
button_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
toServer.close();
fromServer.close();
socket.close();
txtMessage.append("连接已断开~~~");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
button_1.setBounds(270, 50, 80, 20);
panel.add(button_1);
JPanel panel_1 = new JPanel();
panel_1.setBounds(12, 100, 415, 118);
contentPane.add(panel_1);
txtMessage = new JTextArea();
txtMessage.setBackground(Color.LIGHT_GRAY);
txtMessage.setColumns(35);
txtMessage.setRows(10);
txtMessage.setTabSize(4);
txtMessage.setText("客户端\n");
panel_1.add(txtMessage);
txtXiaoxi = new JTextField();
txtXiaoxi.addActionListener(new sendListener());
//txtXiaoxi.setText("xiaoxi");
txtXiaoxi.setBounds(20, 245, 300, 25);
contentPane.add(txtXiaoxi);
txtXiaoxi.setColumns(10);
JButton button_2 = new JButton("发送");
button_2.addActionListener(new sendListener());
button_2.setBounds(330, 245, 60, 25);
contentPane.add(button_2);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String ip = textField_IP.getText();
int port = Integer.parseInt(textField_Port.getText());
try {
socket = new Socket(ip, port);
Client_thread client_thread = new Client_thread();
Thread thread = new Thread(client_thread);
thread.start();
} catch (IOException e1) {
txtMessage.append(e1.toString() + '\n');
}
}
});
this.setSize(600, 420);
this.setLocation(600, 300);
this.add(panel);
this.add(panel_1);
this.setTitle("用户界面");
this.setVisible(true);
}
private class sendListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
try {
//得到当前时间
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // 设置日期格式
String time = df.format(Calendar.getInstance().getTime());
toServer.writeUTF(txtXiaoxi.getText().trim() + '\n');
txtMessage.append( time + "发送的消息:" + txtXiaoxi.getText().trim() +'\n');
txtXiaoxi.setText("");
} catch (IOException e1) {
System.err.println(e1);
}
}
}
//消息收发线程
public class Client_thread implements Runnable{
public void run(){
try {
fromServer = new DataInputStream(socket.getInputStream());
toServer = new DataOutputStream(socket.getOutputStream());
while(true){
String fromStr = fromServer.readUTF();
txtMessage.append("服务端发来消息:" +fromStr);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Client frame = new Client();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO 自动生成的方法存根
}
}
更多相关案例