//客户端
public class TcpClient {
public static void main(String[] args) throws IOException {
Socket s = new Socket("192.168.38.22",2365);
OutputStream os = s.getOutputStream();
DataOutputStream dos =new DataOutputStream(os);
File file = new File("E:/JAVA8/22B9A1D9.gif");
dos.writeUTF(file.getName());
BufferedOutputStream bos = new BufferedOutputStream(os);
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
byte[] b = new byte[1024];
int len;
while ((len = bis.read(b))!=-1) {
bos.write(b, 0, len);
}
s.shutdownOutput();//关闭输出,如果没有此指令,客户端和服务器会互相等待
//接收回复的数据
System.out.println("服务器回复:");
InputStream is = s.getInputStream();
byte[] bytes = new byte[1024];
int read = is.read(bytes);
System.out.println(new String(bytes,0,read));
// bos.close(); /关闭输出指令之后不再需要此关闭流的方法
bis.close();
s.close();
}
}
服务器端
public class TcpServer { public static void main(String[] args) throws IOException { ServerSocket ss = new ServerSocket(2365); while (true) { Socket s = ss.accept(); InputStream is = s.getInputStream(); DataInputStream dis = new DataInputStream(is); String s1 = dis.readUTF(); if (s1.endsWith(".exe")){ System.out.println("格式有误上传失败"); continue; } String ip = s.getInetAddress().getHostAddress(); System.out.println(ip+"正在上传"+s1); BufferedInputStream bis = new BufferedInputStream(is); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("E:/JAVA8/" + System.currentTimeMillis() + s1)); byte[] b = new byte[1024]; int len; while ((len =bis.read(b))!=-1) { bos.write(b, 0, len); System.out.println("标记位..."); } System.out.println("上传成功"); //回复给客户端 OutputStream os = s.getOutputStream(); os.write("上传成功".getBytes()); bos.close(); bis.close(); s.close(); } } }