服务端:
package com.huan.yu1;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class ServerSokcetDemo1 implements Runnable {
private Socket s;
public ServerSokcetDemo1(Socket s) {
super();
this.s = s;
}
/**
* 定义一个线程
*/
@Override
public void run() {
// 读取客户端的数据进行上传
int count = 1;
String ip = s.getInetAddress().getHostAddress();
System.err.println(ip + "---connect");
// 读取客户端发过来得数据
try {
InputStream is = s.getInputStream();
// 定义目的地
byte[] b = new byte[1024 * 4];
File file = new File("F://ppp");
if (!file.exists()) {
file.mkdir();
}
// 重新定义上传文件的路径和名称
File child = new File(file, ip + "00" + count + ".jpg");
// 如果存在就重新创建
while (child.exists()) {
child = new File(file, ip + "00" + count + ".jpg");
}
FileOutputStream fos = new FileOutputStream(child);
int len = 0;
while ((len = is.read(b)) != -1) {
fos.write(b);
}
OutputStream out = s.getOutputStream();
out.write("上传成功".getBytes());
fos.close();
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 客户端上传数据
*
* @throws IOException
*/
@SuppressWarnings("resource")
public static void main(String[] args) throws IOException {
ServerSocket ss = new ServerSocket(10666);
while (true) {
Socket s = ss.accept();
new Thread(new ServerSokcetDemo1(s)).start();;
}
}
}
客户端:
package com.huan.yu1;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
public class ClientSocket {
/**
* 客户端
*
* @throws IOException
* @throws UnknownHostException
*/
@SuppressWarnings("resource")
public static void main(String[] args) throws UnknownHostException, IOException {
// 请求服务,并且要将数据上传上去
//本地ip
Socket s = new Socket("192.168.86.1", 10666);
FileInputStream fis = new FileInputStream("F://picture//1920.png");
OutputStream os = s.getOutputStream();
byte[] b = new byte[1024 * 4];
int len = 0;
while ((len = fis.read(b)) != -1) {
os.write(b);
}
// 告诉服务器读取完毕
s.shutdownOutput();
// 读取服务器的数据
InputStream is = s.getInputStream();
byte[] b1 = new byte[1024 ];
int len1=is.read(b1);
String str=new String(b1,0,len1);
System.err.println(str);
fis.close();
s.close();
is.close();
}
}