Java Socket Client编程

来源:互联网 发布:怎么把域名和ip绑定 编辑:程序博客网 时间:2024/05/21 20:51



import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;


import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.ScrollPaneConstants;


public class ClientAwt implements ActionListener {
    /**
     * @param args
     * 作者:wozijisunfly
     * 作用:实现客户端 图形化界面
     */
    JFrame jf = new JFrame("za-socket-client");
    public static JTextArea jta = new JTextArea(18,200);
    JScrollPane jsp = new JScrollPane(jta);
   
    JRadioButton windows = new JRadioButton("Windows_OS");
    JRadioButton linux = new JRadioButton("Linux_OS");
    JLabel jlip = new JLabel("ip地址 : ");
    JTextField jtfip = new JTextField(15);
    JLabel jlport = new JLabel("端口号 : ");
    JTextField jtfport = new JTextField(4);
    JRadioButton jrb1 = new JRadioButton("执行命令:");
    JRadioButton jrb2 = new JRadioButton("拷贝文件:");
    JRadioButton jrb3 = new JRadioButton("传输文件:");
    JRadioButton jrb4 = new JRadioButton("文件路径:");
   
    JTextField jtfcmd = new JTextField(30);
    JTextField jtffrom = new JTextField(30);
    JTextField jtfto = new JTextField(30);
    JTextField jtfpath = new JTextField(30);
   
    ButtonGroup bg1 = new ButtonGroup();
    ButtonGroup bg2 = new ButtonGroup();
   
    public static JButton jb = new JButton("确定");
    Font f1=new Font("宋体",Font.PLAIN,18);
   
public static String allCMD = "";
 
public static void setAllCMD(String allCMD) {
if (allCMD.split("#").length == 5){
ClientAwt.allCMD = allCMD;
}else {
ClientAwt.allCMD = "";
}

}
public static String getAllCMD() {
return allCMD;
}


public ClientAwt(){
    
jtfcmd.setText("请输入命令!");
jtffrom.setText("源文件地址!");
jtfto.setText("目的文件地址!");
// jtfpath.setText("请输入执行文件的路径!");
 
jtfip.setText(null);
jtfport.setText(null);
 
JPanel totalp = new JPanel(new BorderLayout());
// JPanel upp = new JPanel(new GridLayout(7,1));
JPanel upp = new JPanel(new GridLayout(6,1));
JPanel client = new JPanel(new FlowLayout());
JPanel jp1 = new JPanel(new FlowLayout());
        JPanel jp2 = new JPanel(new FlowLayout());
        JPanel jp3 = new JPanel(new FlowLayout());
        JPanel jp4 = new JPanel(new FlowLayout());
        JPanel jp5 = new JPanel(new FlowLayout());
//        JPanel jp6 = new JPanel(new FlowLayout());
       
        jp1.add(windows);
        jp1.add(linux);
       
        bg1.add(windows);
        bg1.add(linux);
        
        client.add(jlip);
        client.add(jtfip);
        client.add(jlport);
        client.add(jtfport);
        
        jrb1.addActionListener(this);
        jp2.add(jrb1);
        jp2.add(jtfcmd);
        
        jrb2.addActionListener(this);
        jp3.add(jrb2);
        jp3.add(jtffrom);
        
        jrb3.addActionListener(this);
        jp4.add(jrb3);
        jp4.add(jtfto);
        
//        jrb4.addActionListener(this);
//        jp5.add(jrb4);
//        jp5.add(jtfpath);
       
        jb.addActionListener(this);
        jp5.add(jb);
       
        bg2.add(jrb1);
        bg2.add(jrb2);
        bg2.add(jrb3);
        bg2.add(jrb4);
       
        upp.add(jp1);
        upp.add(client);
        upp.add(jp2);
        upp.add(jp3);
        upp.add(jp4);
        upp.add(jp5);
//        upp.add(jp6);
       
        jta.setLineWrap(true);
        jta.setSize(425, 665);
        jta.setEditable(false);
        jta.selectAll();
        jta.setFont(f1);
        jta.setEnabled(true);
        jta.setWrapStyleWord(true);
       
        jsp.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
       
        totalp.add(upp,"North");
        totalp.add(jsp,"Center");
       
        jf.add(totalp);
    }
   
    public void show(){
       
        jf.setSize(450, 687);
        jf.setLocation(260, 0);
        jf.setResizable(false);
        jf.setEnabled(true);
        jf.setVisible(true);
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        jta.append("");
    }
    @Override
    public void actionPerformed(ActionEvent e) {
   
    String cmd = e.getActionCommand();
    File existFile = null;
   
    if("确定".equals(cmd)){
if(bg1.getSelection() == windows.getModel()){
allCMD = "windows";
}else if(bg1.getSelection() == linux.getModel()){
allCMD = "linux";
}else{
// jta.append("请选择操作系统类型!\n");
    return ;
}
    if(jtfip.getText() == null || jtfip.getText().trim().equals("")){
    jta.append("请输入远端机器的ip地址!\n");
    return ;
    }else{
    String ip1 = jtfip.getText().trim();
    String[] ip = ip1.split("\\.");
    if(ip.length !=  4 ){
    jta.append("请校验远端机器的ip地址!\n");
    return ;
    }
    for(int i = 0; i < ip.length; i++){
    if(! ip[i].matches("^[0-9]{1,3}$")){
    jta.append("请校验远端机器的ip地址!\n");
        return ;
    }
    }
    allCMD = allCMD +  "#" + jtfip.getText().trim();
    }
    if(jtfport.getText().trim() == null || jtfport.getText().equals("")){
    jta.append("请输入远端机器的端口号!\n");
    return ;
    }else{
    if(! jtfport.getText().trim().matches("^[0-9]{4}$")){
jta.append("请校验远端机器的端口号!\n");
    return ;
}
    allCMD = allCMD + "#" + jtfport.getText().trim();
    }
    if(bg2.getSelection() == null){
    jta.append("请选择操作命令!\n");
    return ;
    }else{
    if(bg2.getSelection() == jrb1.getModel()){
   
    allCMD = allCMD + "#" + "cmd";
    if(jtfcmd.getText() == null || jtfcmd.getText().trim().equals("")){
    jta.append("输入的执行命令不能为空!\n");
    return ;
    }
    allCMD = allCMD + "#" + jtfcmd.getText().trim();
    }
    if(bg2.getSelection() == jrb2.getModel()){
   
    allCMD = allCMD + "#" + "copy";
    if(jtffrom.getText() == null || jtffrom.getText().trim().equals("") 
    || jtfto.getText() == null || jtfto.getText().trim().equals("")){
    jta.append("源文件地址和目的文件地址都不能为空!\n");
    return ;
    }
    existFile = new File(jtfto.getText().trim());
    if (existFile.getParent() == null || existFile.getName() == null || existFile.getName().equals("")){
    jta.append("目的端文件名或绝对路径错误!\n");
    return ;
    }
    allCMD = allCMD + "#" + jtffrom.getText().trim() + "|" + jtfto.getText().trim();
    }
    if(bg2.getSelection() == jrb3.getModel()){
   
    allCMD = allCMD + "#" + "send";
    if(jtffrom.getText() == null || jtffrom.getText().trim().equals("") 
    || jtfto.getText() == null || jtfto.getText().trim().equals("")){
    jta.append("源文件地址和目的文件地址都不能为空!\n");
    return ;
    }
    existFile = new File(jtffrom.getText().trim());
    if (! existFile.exists()){
    jta.append("输入的源文件不存在!\n");
    return ;
    }
    allCMD = allCMD + "#" + jtffrom.getText().trim() + "|" + jtfto.getText().trim();
    }
    if(bg2.getSelection() == jrb4.getModel()){
   
    allCMD = allCMD + "#" + "path";
    if (jtfpath.getText() == null || jtfpath.getText().trim().equals("")){
    jta.append("输入文件路径不能为空!\n");
    return ;
    }
    existFile = new File(jtfpath.getText().trim());
    if (! existFile.exists()){
    jta.append("输入的文件或绝对路径错误!\n");
    return ;
    }
    allCMD = allCMD + "#" + jtfpath.getText().trim();
    }
    }
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddkkmmssSSS");
    allCMD = sdf.format(new Date()) + "@" + allCMD;
    ClientAwt.setAllCMD(allCMD);
    jb.setEnabled(false);
        }
    if(cmd.equals("执行命令:")){
jtfcmd.setText("");
jtfcmd.setEditable(true);
jtffrom.setText("源文件地址!");
jtfto.setText("目的文件地址!");
jtfpath.setText("请输入执行文件的路径!");
jtffrom.setEditable(false);
jtfto.setEditable(false);
jtfpath.setEditable(false);
}
if(cmd.equals("拷贝文件:")){
jtffrom.setText("");
jtfto.setText("");
jtffrom.setEditable(true);
jtfto.setEditable(true);
jtfcmd.setText("请输入命令!");
jtfpath.setText("请输入执行文件的路径!");
jtfcmd.setEditable(false);
jtfpath.setEditable(false);
}
if(cmd.equals("传输文件:")){
jtffrom.setText("");
jtfto.setText("");
jtffrom.setEditable(true);
jtfto.setEditable(true);
jtfcmd.setText("请输入命令!");
jtfpath.setText("请输入执行文件的路径!");
jtfcmd.setEditable(false);
jtfpath.setEditable(false);
}
// if(cmd.equals("文件路径:")){
// jtfpath.setText("");
// jtfpath.setEditable(true);
// jtffrom.setText("源文件地址!");
// jtfto.setText("目的文件地址!");
// jtfcmd.setText("请输入命令!");
// jtfcmd.setEditable(false);
// jtffrom.setEditable(false);
// jtfto.setEditable(false);
// }
    }
    
    public static String getCommand(){
    ClientAwt.setAllCMD(allCMD);
    return ClientAwt.getAllCMD();
    }


//    public static void main(String[] args) {
//        new ClientAwt().show();
//    }
}


##################################################################


import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


import javax.swing.JButton;
import javax.swing.JTextArea;


import ClientAwt;
/**
 * 
 * @author wozijisunfly
 * @用途:实现socket客户端程序
 *
 */
@SuppressWarnings("static-access")
public class ClientOfZA {
    private static ExecutorService exec = Executors.newCachedThreadPool();
  
public static JTextArea clientJta = new ClientAwt().jta;
    public static JButton jb = new ClientAwt().jb;
    
    private static String IP;
    private static int PORT;
    private String cmd;
    
public static void main(String[] args) throws Exception {  
ClientAwt ca = new ClientAwt();
ca.show(); //调用图形界面
String reciveCMD = null; //从页面接受到的所有命令包括时间和命令
int num = 1; //设置一个判断值
String[] cmd = null; //根据@分割的字符串数组
String allcmd = null; //需要到服务端执行的所有
String date = ""; //对比日期是否一致
   
while (true){ //图形界面发送过来的第一个命令
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (ca.getCommand() == null || ! "".equals(ca.getCommand())){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
reciveCMD = ca.getCommand();
cmd = reciveCMD.split("@");
allcmd = cmd[1];
break;
} else {
reciveCMD = ca.getCommand();
}
        }
       
        while (true){ //图形界面发送过来大于第一次的命令 
        try {
        Thread.sleep(100);
        } catch (InterruptedException e) {
        e.printStackTrace();
        }
        if (! cmd[0].equalsIgnoreCase(date) && num == 1){
        num = 0;
        date = cmd[0];//比较时间是否一致
        }else{
        reciveCMD = ca.getCommand();
        cmd = reciveCMD.split("@");
        if(! cmd[0].equalsIgnoreCase(date)){
        num = 1;
        allcmd = cmd[1];
        }
        continue;
        }
        if (allcmd != null || ! "".equals(allcmd)){
        new ClientOfZA(allcmd);
        }
        }
    }
  
    public ClientOfZA(String cmd) {
    this.cmd = cmd;
    String[] allCMD = this.cmd.split("#");
    this.IP = allCMD[1];
    this.PORT = Integer.parseInt(allCMD[2]);
   
        try {
            Socket socket = new Socket(IP, PORT);
            exec.execute(new Sender(socket,cmd));
            clientJta.append("已经连接到***" + IP + "***主机上!\n\n");
        } catch (Exception e) {
        e.printStackTrace();
        clientJta.append("连接:===" + IP + "===失败!\n\n");
        jb.setEnabled(true);
        }
    }
  
    /** 
     *  客户端执行获得的命令
     */  
    static class Sender implements Runnable {
        private Socket socket;
        private String cmd;
        
        private BufferedReader br = null;
        private PrintWriter pw = null;
        
        private DataInputStream dis = null;
        private DataOutputStream dos = null;
        
        private byte[] data = new byte[1024];
        
        public Sender(Socket socket,String cmd) {
            this.socket = socket;
            this.cmd = cmd;
        }
  
        public void run() {
            try {
            pw = new PrintWriter(socket.getOutputStream(), true);
            br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            dis = new DataInputStream(socket.getInputStream());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日kk时mm分ss秒SSS毫秒");
  
                while (true) {
                long startTime = System.currentTimeMillis();
                clientJta.append("开始时间:" + sdf.format(new Date()) + "!\n");
                pw.println(cmd);
                pw.flush();
                    String[] analysisCMD = cmd.split("#");
                    String path = analysisCMD[4];
                    File file = null;
                    if (analysisCMD[3].equals("cmd")){
                    while (true) {
                    while(dis.available() <= 0) ;//等待接收到的同步数据
                    String returncmd = br.readLine();
                    if (returncmd.equals("success")) {
                    clientJta.append("命令" + analysisCMD[4] + "执行成功!\n");
                    jb.setEnabled(true);
                    break;
                    }
                    if (returncmd.equals("fail")) {
                    clientJta.append("命令" + analysisCMD[4] + "执行失败!\n");
                    jb.setEnabled(true);
                    break;
                    }
                    }
                    long endTime = System.currentTimeMillis();
                    clientJta.append("结束时间:" + sdf.format(new Date()) + "!\n");
                    computeTime(startTime,endTime);
                    }
                    if (analysisCMD[3].equals("send")){
                    String[] filePath = path.split("\\|");
                    file = new File(filePath[0]);
                    String fileExist;
                    while (true){
                    fileExist = br.readLine();
                    if ("nofile".equals(fileExist)){
                    clientJta.append("目的端文件或路径不存在!\n");
                    break;
                    }
                    if("yes".equals(fileExist)){
                    clientJta.append("OK !!可以发送文件!\n");
                   
                    clientSendFile(file);
                   
                    break;
                    }
                    }
                    long endTime = System.currentTimeMillis();
                    clientJta.append("结束时间:" + sdf.format(new Date()) + "!\n");
                    computeTime(startTime,endTime);
                    }
                    if (analysisCMD[3].equals("copy")){
                    String[] filePath = path.split("\\|");
                    file = new File(filePath[1]);
                    String fileExist;
                    while (true){
                    fileExist = br.readLine();
                    if ("nofile".equals(fileExist)){
                    clientJta.append("目的端文件或路径不存在!\n");
                    break;
                    }
                    if("yes".equals(fileExist)){
                    clientJta.append("OK !!可以拷贝文件!\n");
                   
                    clientCopyFile(file);
                   
                    break;
                    }
                    }
                    long endTime = System.currentTimeMillis();
                    clientJta.append("结束时间:" + sdf.format(new Date()) + "!\n");
                    computeTime(startTime,endTime);
                    }
                    if (analysisCMD[3].equals("path")){
                   
                    }
//                  msg = br.readLine();
//                  if (msg.trim().equals("bye")) {
                    pw.close();
                    br.close();
                    dis.close();
                    clientJta.append("执行完毕!\n\n");
//                  socket.close();
//                  exec.shutdownNow();
                    jb.setEnabled(true);
                    break;
//                  }
                }
            } catch (Exception e) {
                e.printStackTrace();
try {
                if (pw != null) pw.close();
                if (br != null) br.close();
                if (dis != null) dis.close();
} catch (IOException e1) {
e1.printStackTrace();
}
                clientJta.append("执行命令失败!\n\n");
                jb.setEnabled(true);
            }
        }
        /**
         * 计算执行时间
         * @param startTime
         * @param endTime
         */
        private void computeTime(long startTime , long endTime){
        long time = endTime - startTime;
        time = time / 1000;
        int hour = (int)(time / 3600);
        time = endTime - startTime;
        time = time / 1000;
        time = time % 3600;
        int minut = (int)(time / 60);
        time = endTime - startTime;
        time = time / 1000;
        time = time % 60;
        int second = (int)time;
        int millisecond = (int)((endTime - startTime) % 1000);
        clientJta.append("执行时间为:" + hour + "小时*" + minut + "分*" + second + "秒*" + millisecond + "毫秒!\n\n");
        jb.setEnabled(true);
        }
        /**
         * client端发送到server端的文件
         * @param file
         */
        private void clientSendFile(File file){
        try {
        int len;
dis = new DataInputStream(new FileInputStream(file));
dos = new DataOutputStream(socket.getOutputStream());
DataInputStream is = new DataInputStream(socket.getInputStream());

dos.write((file.getName() + ";" + file.length()).getBytes());
len = is.read(data);
String start = new String(data, 0, len);

if(start.equals("start")){
while ((len = dis.read(data)) != -1) {
dos.write(data,0,len);
dos.flush();
}
}
clientJta.append("发送文件大小为:"+ file.length() +"字节!\n");
dos.close();
dis.close();
is.close();
} catch (IOException e) {
e.printStackTrace();
clientJta.append("发送文件失败!\n\n");
}
        }
        /**
         * client端拷贝server端的文件
         * @param file
         */
        private void clientCopyFile(File  file){
        try {
        dos = new DataOutputStream(new FileOutputStream(file));
dis = new DataInputStream(socket.getInputStream());
DataOutputStream os = new DataOutputStream(socket.getOutputStream());

int len = dis.read(data);
String[] str = new String(data, 0, len, "utf-8").split(";");
os.write("start".getBytes());

while(dis.available()<=0) ;//等待同步

while ((len = dis.read(data)) != -1) {
dos.write(data,0,len);
dos.flush();
}
clientJta.append("接收文件名为:" + str[0] +"\n");
clientJta.append("大小为: " + str[1] + "  字节\n");
clientJta.append("接收到的文件路径及文件名为:" + file.getPath() + "\n");
clientJta.append("接收文件大小为: "+ file.length() +"  字节!\n");
dos.close();
dis.close();
os.close();
} catch (IOException e) {
e.printStackTrace();
clientJta.append("发送文件失败!\n\n");
}
        }
    }
}
0 0
原创粉丝点击