client
public void createConnection() throws UnknownHostException, RefusedException, SocketTimeoutException
{
try {
socket = new Socket();
SocketAddress address =new InetSocketAddress(this.hostUri, hostPort);
socket.connect(address, 5000);
logger.info("Socket server "+hostUri+" is connected");
}catch (UnknownHostException e) {
e.printStackTrace();
throw new UnknownHostException();
}catch(SocketTimeoutException e)
{
e.printStackTrace();
throw new SocketTimeoutException();
}
catch (IOException e) {
e.printStackTrace();
throw new RefusedException();
}
}
public boolean send()throws UnknownHostException,RefusedException, SocketTimeoutException ,SendException
{
boolean result = false;
createConnection();
writer = getWriter();
reader = getReader();
try {
writer.writeUTF(fileName);
writer.flush();
writer.writeLong(size);
writer.flush();
write(writer, reader);
writer.flush();
BufferedReader r = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
String line="";
while (true) {
line = r.readLine();
if (line.equals("End"))
{
result =true;
break;
}
}
}
catch (IOException e) {
e.printStackTrace();
throw new SendException();
}finally
{
close();
}
return result;
}
protected void write(DataOutputStream dos,DataInputStream dis) throws IOException
{
byte [] buf =new byte [2048];
int read = 0;
while((read=dis.read(buf))!=-1)
{
dos.write(buf,0,read);
}
}
protected DataOutputStream getWriter()
{
try {
writer = new DataOutputStream(socket.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
return this.writer;
}
protected DataInputStream getReader()
{
return this.reader;
}
protected void close() {
try {
reader.close();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
server
public void run() {
String filePath="";
try {
dis = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
String fileName = dis.readUTF();
if(fileName.toLowerCase().indexOf(".jar")>0)
{
filePath=jarUploadPath+"//"+ fileName;
}else
{
filePath=xmlUploadPath+"//"+ fileName;
}
Long lth = dis.readLong();
File file = new File(filePath);
dos = new DataOutputStream(new FileOutputStream(file));
byte[] buf = new byte[1024];
int read = 0;
long tmp = 0;
log.info("正在接收文件:"+filePath+",大小:"+lth+"kb");
while ((read = dis.read(buf)) != -1) {
dos.write(buf, 0, read);
tmp+=read;
if(lth==tmp)
{
break;
}
}
PrintWriter pw = new PrintWriter(socket.getOutputStream());
log.info("文件接收完成:"+filePath);
pw.write("End");
pw.flush();
} catch (IOException e) {
log.error("文件接收错误:"+filePath);
e.printStackTrace();
} finally {
try {
dis.close();
dos.flush();
dos.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
socket send receive
最新推荐文章于 2023-02-24 08:10:27 发布