A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 张超 中级黑马   /  2012-12-19 14:28  /  1358 人查看  /  2 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

package itheima.cn;
import java.awt.FileDialog;
import java.awt.FlowLayout;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import javax.swing.JButton;
import javax.swing.JFrame;
public class UpLoadDemo {
/**
  * @param args
  */
JFrame f = new JFrame();
FileDialog fd = new FileDialog(f, "请选择你要上传的文件", FileDialog.LOAD);
TextField tf = new TextField(10);
JButton jb1 = new JButton("确认上传");
public UpLoadDemo(){
  
  JButton jb = new JButton("查找上传文件");
  f.setSize(400, 200);
  f.setLayout(new FlowLayout());
  f.add(jb);
  f.add(tf);
  f.add(jb1);
  f.setVisible(true);
  
  jb.addActionListener(new ActionListener() {
   
   @Override
   public void actionPerformed(ActionEvent e) {
    fd.setVisible(true);
    if(fd.getDirectory() != null){
     tf.setText("");
     tf.setText(fd.getDirectory());
    }
   }
  });
  
  jb1.addActionListener(new ActionListener() {//给上传按钮注册事件,
   
   @SuppressWarnings("deprecation")
   @Override
   public void actionPerformed(ActionEvent e) {//建立客服端
    Socket s;
    try {
     
     s = new Socket("192.168.1.102", 11000);//    这个地方报java.net.ConnectException ,我是先开启服务端了的

     System.out.println(s.getInetAddress());
     FileInputStream fins = new FileInputStream("F://1.txt");
     OutputStream ous = s.getOutputStream();
     byte[] buf = new byte[1024];
     int len = -1;
     System.out.println("haha");
     while((len=fins.read(buf))!=-1){
      ous.write(buf, 0, len);
     }
     
     //打一个结束标记
     s.shutdownOutput();
     InputStream ins = s.getInputStream();
     byte[] buf_2 = new byte[1024];
     int num = ins.read(buf_2);
     System.out.println(new String(buf_2, num));
     s.close();
     fins.close();
     
    } catch (Exception e1) {
     e1.printStackTrace();
    }
   
   }
  });
  
}
public static void main(String[] args) {
  // TODO Auto-generated method stub
  
  new UpLoadDemo();
  
}
}
//服务端
class SocketServer{
public SocketServer(){
  try {
   ServerSocket ss = new ServerSocket(11000);
   Socket s =ss.accept();
   InputStream ins = s.getInputStream();
   FileOutputStream fos = new FileOutputStream("F://copy.txt");
   byte[] buf = new byte[1024];
   int len ;
   while((len =ins.read(buf))!=-1){
    fos.write(buf, 0, len);
   }
   
   OutputStream ous = s.getOutputStream();
   ous.write(new String("上传成功").getBytes());
   ss.close();
   s.close();
   fos.close();
  }
  catch (IOException e) {
   e.printStackTrace();
  }
}
public static void main(String[] args){
  new SocketServer();
}
}

2 个回复

倒序浏览
看看你的11000端口有没有冲突,或者有没有开启端口
回复 使用道具 举报
高境 发表于 2012-12-19 14:36
看看你的11000端口有没有冲突,或者有没有开启端口

哥们  没有啊,有空吗帮我调试一下:loveliness:
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马