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();
}
}
|
|