Client
package sunxu.util;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import javax.swing.BorderFactory;
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;
public class Client extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
private PrintWriter writer; // 声明PrintWriter类对象
private BufferedReader reader; // 声明BufferedReader对象
private Socket socket; // 声明Socket对象
JTextArea ta_info; // 创建JtextArea对象
JButton button1 = new JButton("Connect");
private String sendIp;
private int sendPort=4000;
private void getIp(){
try {
InetAddress inetAddr = InetAddress.getLocalHost();// 创建本地主机的InetAddress对象
sendIp= inetAddr.getHostAddress();// 获得本地主机的IP地
} catch (UnknownHostException e1) {
e1.printStackTrace();
}
}
private int index = -1;
private void connect() { // 连接套接字方法
try { // 捕捉异常
getIp();
socket = new Socket(sendIp,sendPort); // 实例化Socket对象
while (true) {
writer = new PrintWriter(socket.getOutputStream(), true);// 创建输出流对象
reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); // 实例化BufferedReader对象
index = Integer.parseInt(reader.readLine());// 获得客户登录服务器的索引值
//ta_info.append("你是第"+(index+1)+"个完成连接的用户。\n"); // 文本域中提示信息
getServerInfo();
}
} catch (Exception e) {
e.printStackTrace(); // 输出异常信息
}
}
public static void main(String[] args) { // 主方法
Client clien = new Client(); // 创建本例对象
clien.setVisible(true); // 将窗体显示
clien.connect(); // 调用连接方法
}
private void getServerInfo() {
try {
while (true) { // 如果套接字是连接状态
if (reader != null) {
String line = reader.readLine();// 读取服务器发送的信息
if (line != null){
ta_info.append("接收到服务器发送的信息:" + line + "\n"); // 获得客户端信息
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (reader != null) {
reader.close();// 关闭流
}
if (socket != null) {
socket.close(); // 关闭套接字
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* Create the frame
*/
public Client() {
super();
addWindowListener(new WindowAdapter() {
public void windowClosing(final WindowEvent e) {
writer.println(String.valueOf(index));// 向服务器端发送退出客户的索引值
}
});
setTitle("客户端");//窗口标题
setBounds(100, 100, 361, 257); //设置位置和大小
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //设置窗口关闭
final JPanel panel = new JPanel(); //新建容器,放在窗口正上方
getContentPane().add(panel, BorderLayout.NORTH);
panel.setBorder(BorderFactory.createTitledBorder("客户机设置:")); //容器标题
final JLabel label = new JLabel(); //标签
label.setText("Server IP:"); //标签名Sever Ip;
panel.add(label); //添加到容器中
JTextField tf_sen= new JTextField(); //文本域
tf_sen.setPreferredSize(new Dimension(50, 25));//长宽大小
getIp();
tf_sen.setText(sendIp);
panel.add(tf_sen);
final JLabel label1 = new JLabel(); //标签
label1.setText("Server Port:"); //标签名Sever Port
panel.add(label1); //添加到容器中
JTextField tf_Port = new JTextField();
tf_Port.setPreferredSize(new Dimension(50, 25));
tf_Port.setText(sendPort+"");
panel.add(tf_Port);
final JButton button1 = new JButton("Connect"); //链接按钮
button1.addActionListener(new ActionListener() { //事件,显示连接成功
public void actionPerformed(final ActionEvent e) {
ta_info.append("Connect to server…\n");
ta_info.append("你是第"+(index+1)+"个完成连接的用户。\n"); // 文本域中提示信息
writer.println("Client connected…");
}
});
panel.add(button1);//添加到容器中
final JPanel panel_1 = new JPanel();
getContentPane().add(panel_1, BorderLayout.SOUTH);//容器放到窗口的下方
final JLabel label_1 = new JLabel();
label_1.setText("Say:"); //标签Say
panel_1.add(label_1);
final JTextField tf_send = new JTextField(); //文本域
tf_send.setPreferredSize(new Dimension(220, 25)); //设置大小,长度
panel_1.add(tf_send);
final JButton button = new JButton();
button.addActionListener(new ActionListener() {//添加按钮事件,发送信息到客户端,并且显示在文本域中
public void actionPerformed(final ActionEvent e) {
writer.println(tf_send.getText()); // 将文本框中信息写入流
ta_info.append("客户端发送的信息:" + tf_send.getText()
+ "\n"); // 将文本框中信息显示在文本域中
tf_send.setText(""); // 将文本框清空
}
});
button.setText("Say");
panel_1.add(button);
final JScrollPane scrollPane = new JScrollPane();
getContentPane().add(scrollPane, BorderLayout.CENTER);//将滑轮放在窗口的中间
ta_info = new JTextArea();
scrollPane.setViewportView(ta_info); //将文本域放在滚动轴中
}
}
Server
package sunxu.util;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.net.*;
import java.util.Vector;
import javax.swing.BorderFactory;
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;
public class Server extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
private JTextArea ta_info;
private ServerSocket server; // 声明ServerSocket对象
private Socket socket; // 声明Socket对象socket
private int sendPort=4000;
private Vector
private int counts = 0;// 用于记录连接的客户人数
public void getServer() {
try {
server = new ServerSocket(sendPort); // 实例化Socket对象
while (true) { // 如果套接字是连接状态
socket = server.accept(); // 实例化Socket对象
counts++;
PrintWriter out = new PrintWriter(socket.getOutputStream(),
true);
out.println(String.valueOf(counts - 1));// 向客户端发送套接字索引
vector.add(socket);// 存储客户端套接字对象
new ServerThread(socket).start();// 创建并启动线程序
}
} catch (Exception e) {
e.printStackTrace(); // 输出异常信息
}
}
class ServerThread extends Thread {
Socket socket = null; // 创建Socket对象
BufferedReader reader; // 声明BufferedReader对象
public ServerThread(Socket socket) { // 构造方法
this.socket = socket;
}
public void run() {
try {
if (socket != null) {
reader = new BufferedReader(new InputStreamReader(socket
.getInputStream())); // 实例化BufferedReader对象
int index = -1;// 存储退出的客户端索引值
try {
while (true) { // 如果套接字是连接状态
String line = reader.readLine();// 读取客户端信息
try {
index = Integer.parseInt(line);// 获得退出的客户端索引值
} catch (Exception ex) {
index = -1;
}
if (line != null && line.equals("Client connected…"))
ta_info.append("第" + counts + line + "\n"); // 显示客户端发送的信息
if(line!=null&&line.equals("Client connected…")==false)
ta_info.append("接收到客户机发送的信息:" + line + "\n"); // 显示客户端发送的信息
}
} catch (Exception e) {
if (index != -1) {
vector.set(index, null);// 将退出的客户端套接字设置为null
ta_info.append("第" + (index + 1) + "个客户端已经退出。\n"); // 输出异常信息
}
} finally {
try {
if (reader != null) {
reader.close();// 关闭流
}
if (socket != null) {
socket.close(); // 关闭套接字
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
private void writeInfo(PrintWriter writer, String text) {
writer.println(text);
}
public static void main(String[] args) { // 主方法
Server frame = new Server(); // 创建本类对象
frame.setVisible(true);// 显示窗体
frame.getServer(); // 调用方法
}
public Server() {
super();
setTitle("服务器"); //窗口标题
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //设置窗口关闭
setBounds(100, 100, 379, 260); //设置位置和大小
final JScrollPane scrollPane = new JScrollPane(); //添加滚动轴
getContentPane().add(scrollPane, BorderLayout.CENTER);//将滚动轴放在窗口的中间
ta_info = new JTextArea(); //添加文本域
scrollPane.setViewportView(ta_info); //创建一个视口
final JPanel panel = new JPanel();
getContentPane().add(panel, BorderLayout.SOUTH); //容器放在窗口的下方
final JLabel label = new JLabel();//新的标签
label.setText("Say:");//标签的内容
panel.add(label);
final JTextField tf_send = new JTextField();//文本框
tf_send.setPreferredSize(new Dimension(220, 25));//文本框长度和宽度
panel.add(tf_send);
final JButton button = new JButton();
button.addActionListener(new ActionListener() {//按钮监听事件
public void actionPerformed(final ActionEvent e) {//将信息发送给客户机
for (int i = 0; i < vector.size(); i++) {
Socket socket = vector.get(i);// 获得连接成功的套接字对象
PrintWriter writer;
try {
if (socket != null && !socket.isClosed()) {
writer = new PrintWriter(socket.getOutputStream(),
true);// 创建输出流对象
writeInfo(writer, tf_send.getText()); // 将文本框中信息写入流
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
ta_info.append("服务器发送的信息是:" + tf_send.getText() + "\n"); // 将文本框中信息显示在文本域中
tf_send.setText(""); // 将文本框清空
}
});
button.setText("Say:");
panel.add(button);
final JPanel panel_1 = new JPanel();//新建容器
getContentPane().add(panel_1, BorderLayout.NORTH);//放在窗口的上方
panel_1.setBorder(BorderFactory.createTitledBorder("服务器设置:"));//容器的标题
final JLabel label_1 = new JLabel();//标签
label_1.setText("Port:");//标签名称Port
JTextField tf_sen= new JTextField();
tf_sen.setPreferredSize(new Dimension(220, 25)); //文本框的长度和宽度
tf_sen.setText(sendPort+""); //转换类型
panel_1.add(label_1);
panel_1.add(tf_sen);
final JButton button1 = new JButton("Strat");//新建按钮Start
button1.addActionListener(new ActionListener() { //按钮监听事件,打印文字,提示开始搜索客户机
public void actionPerformed(final ActionEvent e) {
ta_info.append("Server starting…"+"\n");
}
});
panel_1.add(button1);
}
}