import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Random;
public class DemoServer {
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(8888);
while (true) {
Socket socket = server.accept();
new Thread(new Runnable() {
@Override
public void run() {
try {
InputStream is = socket.getInputStream();
File file = new File("E:\\tupian");
if (!file.exists()){
file.mkdir();
}
String fileName="itcase"+System.currentTimeMillis()+new Random().nextInt(999999)+".jpg";
FileOutputStream fos = new FileOutputStream(file+"\\"+fileName)
int len=0;
byte[] bytes = new byte[1024];
while ((len=is.read(bytes))!=-1){
fos.write(bytes,0,len);
}
socket.getOutputStream().write("上传成功".getBytes());
fos.close();
server.close();
socket.close();
}catch (IOException e){
System.out.println(e);
}
}
}).start();
}
}
}
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
public class DemoServer {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("127.0.0.1",8888);
OutputStream os = socket.getOutputStream();
os.write("你好,服务器!".getBytes());
InputStream is = socket.getInputStream();
byte[] bytes = new byte[1024];
int len=is.read(bytes);
System.out.println(new String(bytes,0,len));
is.close();
socket.close();
}
} |
|