借着上次回顾到socket的资料,这次完成一个c/s端的socket示例。主要回顾io、socket、swing、thread 。
下一个学习的重点是nio和mina框架,不知道各位同仁能否指点一二,或者在学习nio的时候有什么建议,或者学习的方法,谢谢大家了。
以前长期潜水,现在在写这些学生时代的代码,少不得拍砖,谢谢拍砖。
服务器端:
package com.jzpark.socket; import java.awt.FileDialog; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JTextArea; import javax.swing.JTextField; import com.swtdesigner.SwingResourceManager; /** * @author: antxuan * @createtime: 2010-5-29 下午08:40:18 * @Description: socket客户端 */ public class Server { private static final long serialVersionUID = 1L; JFrame jf = new JFrame("socket通信服务器端"); // 在现人数 // 连接到主机socket的ip地址列表 // 客户端发送来的信息 final JTextArea txtAMessage = new JTextArea(); // 服务器端回复信息 final JTextField txtRMessage = new JTextField(); final JLabel lblMessage = new JLabel(); // 得到操作系统平台下的文件分隔符 final String separator = System.getProperty("line.separator"); // 保存客户端发来的数据 记录ip地址和消息 private List<String> list = new ArrayList<String>(); SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd ss:hh:mm"); SimpleDateFormat format2=new SimpleDateFormat("sshhmm"); // 取得输入流 DataInputStream dis = null; // 取得输出流 DataOutputStream dos = null; // 服务器套接字 ServerSocket serverSocket = null; // 套接字 Socket socket = null; // 创建窗体 private void createFrame() { jf.getContentPane().setLayout(null); jf.setSize(431, 395); JLabel jlmessage = new JLabel("当前连接服务器人数:"); jf.add(jlmessage); final JLabel label = new JLabel(); label.setBounds(35, 19, 66, 30); label.setText("启动状态:"); jf.getContentPane().add(label); final JButton btnOn = new JButton(); btnOn.setBounds(247, 20, 138, 29); btnOn.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { // new ServerSocketThread(); btnOn.setEnabled(false); new ServerSocketThread().start(); lblMessage.setText("已启动..."); lblMessage.setIcon(SwingResourceManager.getIcon(Server.class, "ajax-loader.gif")); } }); btnOn.setText("启动服务器socket"); jf.getContentPane().add(btnOn); final JLabel lblmessage = new JLabel(); lblmessage.setName(""); lblmessage.setText(""); lblmessage.setBounds(292, 201, 66, 18); jf.getContentPane().add(lblmessage); final JLabel label_1 = new JLabel(); label_1.setText("接收到的消息:"); label_1.setBounds(10, 75, 91, 18); jf.getContentPane().add(label_1); txtAMessage.setEditable(false); txtAMessage.setBounds(107, 75, 278, 142); jf.getContentPane().add(txtAMessage); final JLabel label_3 = new JLabel(); label_3.setText("回复信息:"); label_3.setBounds(10, 256, 66, 18); jf.getContentPane().add(label_3); txtRMessage.setBounds(107, 254, 278, 22); jf.getContentPane().add(txtRMessage); lblMessage.setText(""); lblMessage.setBounds(107, 15, 91, 39); jf.getContentPane().add(lblMessage); final JButton button_1 = new JButton(); button_1.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { // if(socket.isBound()){ // JOptionPane.showMessageDialog(jf,"没有连接!:"); // // } String message = txtRMessage.getText(); if(message.equals("")){ JOptionPane.showMessageDialog(jf, "请输入回复信息"); return; } // 当点击发送按钮后,将发送消息框清空 txtRMessage.setText(""); try { String date=format.format(new Date()); txtAMessage.append(date+"您的回复:" + message + separator); dos.writeUTF(message ); dos.flush(); } catch (IOException e1) { e1.printStackTrace(); } } }); button_1.setText("发送"); button_1.setBounds(152, 305, 102, 29); jf.getContentPane().add(button_1); final JButton btnClose = new JButton(); btnClose.setText("关闭socket"); btnClose.setBounds(23, 305, 102, 28); jf.getContentPane().add(btnClose); btnClose.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { // ServerSockets sc=new ServerSockets(new Socket()); btnOn.setEnabled(true); btnClose.setEnabled(false); lblMessage.setText("已关闭!"); if (socket != null) { if (!socket.isClosed()) { try { socket.close(); } catch (IOException e1) { e1.printStackTrace(); } } } } }); // 禁止用户设置窗体大小 jf.setResizable(false); jf.addWindowListener(new WindowListener() { public void windowActivated(WindowEvent e) { } public void windowClosed(WindowEvent e) { } public void windowClosing(WindowEvent e) { Runtime.getRuntime().exit(0); try { if(socket!=null){ if(!socket.isClosed()){ socket.close(); } } } catch (IOException e1) { e1.printStackTrace(); } } public void windowDeactivated(WindowEvent e) { } public void windowDeiconified(WindowEvent e) { } public void windowIconified(WindowEvent e) { } public void windowOpened(WindowEvent e) { } }); jf.show(); final JButton button_1_1 = new JButton(); button_1_1.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { FileDialog fd=new FileDialog(jf,"保存聊天信息",FileDialog.SAVE ); fd.show(); byte[] b= txtAMessage.getText().getBytes(); try { String fileName=fd.getDirectory()+fd.getFile()+format2.format(new Date())+".txt"; FileOutputStream fos=new FileOutputStream(fileName); fos.write(b); JOptionPane.showMessageDialog(jf, "对话信息已经保存在"+fileName+"中"); } catch (FileNotFoundException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } } }); button_1_1.setText("导出信息"); button_1_1.setBounds(283, 305, 102, 29); jf.getContentPane().add(button_1_1); } class ServerSocketThread extends Thread { public void run() { try { serverSocket = new ServerSocket(3333); while (true) { socket = serverSocket.accept(); dis = new DataInputStream(socket.getInputStream()); dos = new DataOutputStream(socket.getOutputStream()); txtAMessage.append(socket.getLocalAddress() + "说:" + dis.readUTF() + separator); } } catch (IOException e) { e.printStackTrace(); } } } public static void main(String[] args) { Server server = new Server(); server.createFrame(); } }
客户端:
package com.jzpark.socket;
import java.awt.FileDialog; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.net.Socket; import java.text.SimpleDateFormat; import java.util.Date; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JTextArea; import javax.swing.JTextField; /** * @author: antxuan * @createtime: 2010-5-29 下午08:40:11 * @Description: socket服务器端 */ public class Client { static JFrame jf = new JFrame(); // 聊天记录 final JTextArea txtARecode = new JTextArea(); //发送消息 final JTextField txtRMessage = new JTextField(); // 得到操作系统平台下的文件分隔符 final String separator = System.getProperty("line.separator"); //套接字 private Socket socket=null; // 取得输入流 DataInputStream dis = null; // 取得输出流 DataOutputStream dos = null; //ip地址 String address; //端口 int port; SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd ss:hh:mm"); SimpleDateFormat format2=new SimpleDateFormat("sshhmm"); // 构建窗体 public Client() { jf.setSize(440, 375); jf.getContentPane().setLayout(null); jf.setTitle("socket客户端连接工具"); final JLabel label = new JLabel(); label.setText("IP地址:"); label.setBounds(26, 10, 50, 18); jf.getContentPane().add(label); final JLabel label_1 = new JLabel(); label_1.setText("端口号:"); label_1.setBounds(26, 34, 59, 18); jf.getContentPane().add(label_1); final JTextField txtAddress = new JTextField(); txtAddress.setBounds(82, 8, 152, 22); jf.getContentPane().add(txtAddress); final JTextField txtPort = new JTextField(); txtPort.setBounds(82, 32, 152, 22); jf.getContentPane().add(txtPort); final JButton btnConnect = new JButton(); btnConnect.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { //为ip地址和端口赋值 address=txtAddress.getText(); if(address.equals("")){ JOptionPane.showMessageDialog(jf,"请输入ip地址如:10.1.110.4"); return; } try { if(txtPort.getText().equals("")){ JOptionPane.showMessageDialog(jf,"请输入端口号"); return; } port=Integer.parseInt(txtPort.getText()); } catch (NumberFormatException e2) { JOptionPane.showMessageDialog(jf,"端口号必须为数字"); return; } // 创建连接 new ClientSocketThread().start(); JOptionPane.showMessageDialog(jf,"已经连接到"+address+"的"+port+"端口"); } }); btnConnect.setText("连接"); btnConnect.setBounds(292, 29, 87, 28); jf.getContentPane().add(btnConnect); final JLabel label_2 = new JLabel(); label_2.setText("发送消息:"); label_2.setBounds(10, 253, 66, 18); jf.getContentPane().add(label_2); txtRMessage.setBounds(82, 251, 297, 22); jf.getContentPane().add(txtRMessage); final JButton button = new JButton(); button.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { //取得发送信息 String message=txtRMessage.getText(); txtRMessage.setText(""); if(message.equals("")){ JOptionPane.showMessageDialog(jf,"发送消息不能为空"); return; } String date=format.format(new Date()); txtARecode.append(date+"您说:"+message+separator); try { dos.writeUTF(message); } catch (IOException e1) { e1.printStackTrace(); } } }); button.setText("发送"); button.setBounds(100, 307, 87, 28); jf.getContentPane().add(button); final JLabel label_3 = new JLabel(); label_3.setText("聊天记录:"); label_3.setBounds(10, 73, 66, 18); jf.getContentPane().add(label_3); txtARecode.setBounds(82, 73, 297, 148); txtARecode.setAutoscrolls(true); jf.getContentPane().add(txtARecode); final JButton button_1 = new JButton(); button_1.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { FileDialog fd=new FileDialog(jf,"保存聊天信息",FileDialog.SAVE ); fd.show(); String message=txtARecode.getText(); try { String fileName=fd.getDirectory()+fd.getFile()+format2.format(new Date())+".txt"; FileOutputStream fos = new FileOutputStream(fileName); fos.write(message.getBytes()); JOptionPane.showMessageDialog(jf,"对话信息已经保存在"+fileName+"中"); } catch (FileNotFoundException e1) { e1.printStackTrace(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } }); button_1.setText("导出聊天记录"); button_1.setBounds(218, 307, 125, 28); jf.getContentPane().add(button_1); txtARecode.setEditable(false); jf.setResizable(false); jf.setLocation(220, 220); jf.show(); jf.addWindowListener(new WindowListener() { public void windowActivated(WindowEvent e) { } public void windowClosed(WindowEvent e) { } public void windowClosing(WindowEvent e) { Runtime.getRuntime().exit(0); try { if(socket!=null){ if(!socket.isClosed()){ socket.close(); } } } catch (IOException e1) { e1.printStackTrace(); } } public void windowDeactivated(WindowEvent e) { } public void windowDeiconified(WindowEvent e) { } public void windowIconified(WindowEvent e) { } public void windowOpened(WindowEvent e) { } }); } public static void main(String[] args) { new Client(); } class ClientSocketThread extends Thread { public void run() { try { while (true) { socket=new Socket(address,port); dis = new DataInputStream(socket.getInputStream()); dos = new DataOutputStream(socket.getOutputStream()); //服务器端返回数据 String message=dis.readUTF(); txtARecode.append("服务器返回:"+message+separator); } } catch (Exception e) { e.printStackTrace(); JOptionPane.showMessageDialog(jf,"不能连接目标主机或端口:"+e.getMessage()); try { if(socket!=null){ if(!socket.isClosed()){ socket.close(); } } } catch (IOException e1) { e1.printStackTrace(); } } } } }