ASP.Net+Android+IOS开发.Net培训期待与您交流!
多个客户端可以并发的上传图片到服务器中
import java.io.*;
import java.net.*;
class PicClient2{
public static void main(String[] args){
try{
//获取客户端Socket,并绑定服务器主机和端口。
Socket s = new Socket(InetAddress.getLocalHost(),10003);
FileInputStream fs = new FileInputStream("d:/tempFile/QQ.png");
OutputStream osOut = s.getOutputStream();
byte[] buf = new byte[1024];
int a = -1;
//将图片读入流中,并写道Socket的OutputStream()流中
while((a=fs.read(buf))!= -1){
osOut.write(buf,0,a);
}
//给网络流加结束标记
s.shutdownOutput();
//读取服务器返回的数据信息
InputStream osIn = s.getInputStream();
byte[] arr = new byte[1024];
int b = osIn.read(buf);
System.out.println(new String(arr,0,b));
osIn.close();
osOut.close();
fs.close();
s.close();
}catch(UnknownHostException e){
throw new RuntimeException("找不到服务器主机");
}catch(IOException e){
throw new RuntimeException("读写文件错误");
}
}
}
//如何实现多线程技术呢?只需将每个客户端的代码存入run方法中即可!
class SockThread implements Runnable{
private Socket s;
String ip;
SockThread(Socket s ){
this.s = s;
}
public void run(){
try{
//获取客户端ip地址
ip = s.getLocalAddress().getHostAddress();
System.out.println(ip+"connect");
InputStream isIn = s.getInputStream();
int count = 1;
File f = new File("d:/tempFile/"+ip+"("+count+")"+".png");
while(f.exists()){
f = new File("d:/tempFile/"+ip+"("+(count++)+")"+".png");
}
//将客户端传过来的图片保存到一个文件夹中
FileOutputStream fos = new FileOutputStream(f);
byte[] buf = new byte[1024];
int a = -1;
while((a = isIn.read(buf))!=-1){
fos.write(buf,0,a);
}
//往客户端写返回信息
OutputStream osOut = s.getOutputStream();
osOut.write("上传成功".getBytes());
fos.close();
isIn.close();
osOut.close();
s.close();
}catch(IOException e){
throw new RuntimeException(ip+"上传失败");
}
}
}
class PicServer2{
public static void main(String[] args){
try{
ServerSocket ss = new ServerSocket(10003);
while(true){
//阻塞式等待客户端发来的请求
Socket s = ss.accept();
//启动线程并把客户端的Socket对象传入处理程序中
new Thread(new SockThread(s)).start();
}
}catch(IOException e){
throw new RuntimeException("服务器端接收失败");
}
}
}
运行结果为