java socket传输图片

转自http://chwshuang.iteye.com/blog/1073715


服务器端:
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerTest {
int port = 8821;

void start() {
Socket s = null;
try {
ServerSocket ss = new ServerSocket(port);
while (true) {
// 选择进行传输的文件
String filePath = "D:\\update\\image\\5.jpg";
File fi = new File(filePath);

System.out.println("文件长度:" + (int) fi.length());

// public Socket accept() throws
// IOException侦听并接受到此套接字的连接。此方法在进行连接之前一直阻塞。

s = ss.accept();
System.out.println("建立socket链接");
DataInputStream dis = new DataInputStream(new BufferedInputStream(s.getInputStream()));
dis.readByte();

DataInputStream fis = new DataInputStream(new BufferedInputStream(new FileInputStream(filePath)));
DataOutputStream ps = new DataOutputStream(s.getOutputStream());
//将文件名及长度传给客户端。这里要真正适用所有平台,例如中文名的处理,还需要加工,具体可以参见Think In Java 4th里有现成的代码。
ps.writeUTF(fi.getName());
ps.flush();
ps.writeLong((long) fi.length());
ps.flush();

int bufferSize = 8192;
byte[] buf = new byte[bufferSize];

while (true) {
int read = 0;
if (fis != null) {
read = fis.read(buf);
}

if (read == -1) {
break;
}
ps.write(buf, 0, read);
}
ps.flush();
// 注意关闭socket链接哦,不然客户端会等待server的数据过来,
// 直到socket超时,导致数据不完整。
fis.close();
s.close();
System.out.println("文件传输完成");
}

} catch (Exception e) {
e.printStackTrace();
}
}

public static void main(String arg[]) {
new ServerTest().start();
}
}



具体实现:
package serverphoto;


import java.net.*;
import java.io.*;

public class ClientSocket {
private String ip;

private int port;

private Socket socket = null;

DataOutputStream out = null;

DataInputStream getMessageStream = null;

public ClientSocket(String ip, int port) {
this.ip = ip;
this.port = port;
}

/** *//**
* 创建socket连接
*
* @throws Exception
* exception
*/
public void CreateConnection() throws Exception {
try {
socket = new Socket(ip, port);
} catch (Exception e) {
e.printStackTrace();
if (socket != null)
socket.close();
throw e;
} finally {
}
}

public void sendMessage(String sendMessage) throws Exception {
try {
out = new DataOutputStream(socket.getOutputStream());
if (sendMessage.equals("Windows")) {
out.writeByte(0x1);
out.flush();
return;
}
if (sendMessage.equals("Unix")) {
out.writeByte(0x2);
out.flush();
return;
}
if (sendMessage.equals("Linux")) {
out.writeByte(0x3);
out.flush();
} else {
out.writeUTF(sendMessage);
out.flush();
}
} catch (Exception e) {
e.printStackTrace();
if (out != null)
out.close();
throw e;
} finally {
}
}

public DataInputStream getMessageStream() throws Exception {
try {
getMessageStream = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
return getMessageStream;
} catch (Exception e) {
e.printStackTrace();
if (getMessageStream != null)
getMessageStream.close();
throw e;
} finally {
}
}

public void shutDownConnection() {
try {
if (out != null)
out.close();
if (getMessageStream != null)
getMessageStream.close();
if (socket != null)
socket.close();
} catch (Exception e) {

}
}
}




客户端:
package serverphoto;


import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileOutputStream;

public class ClientTest {
private ClientSocket cs = null;

private String ip = "localhost";// 设置成服务器IP

private int port = 8821;

private String sendMessage = "Windwos";

public ClientTest() {
try {
if (createConnection()) {
sendMessage();
getMessage();
}

} catch (Exception ex) {
ex.printStackTrace();
}
}

private boolean createConnection() {
cs = new ClientSocket(ip, port);
try {
cs.CreateConnection();
System.out.print("连接服务器成功!" + "\n");
return true;
} catch (Exception e) {
System.out.print("连接服务器失败!" + "\n");
return false;
}

}

private void sendMessage() {
if (cs == null)
return;
try {
cs.sendMessage(sendMessage);
} catch (Exception e) {
System.out.print("发送消息失败!" + "\n");
}
}

private void getMessage() {
if (cs == null)
return;
DataInputStream inputStream = null;
try {
inputStream = cs.getMessageStream();
} catch (Exception e) {
System.out.print("接收消息缓存错误\n");
return;
}

try {
//本地保存路径,文件名会自动从服务器端继承而来。
String savePath = "D:\\update\\";
int bufferSize = 8192;
byte[] buf = new byte[bufferSize];
int passedlen = 0;
long len=0;

savePath += inputStream.readUTF();
DataOutputStream fileOut = new DataOutputStream(new BufferedOutputStream(new BufferedOutputStream(new FileOutputStream(savePath))));
len = inputStream.readLong();

System.out.println("文件的长度为:" + len + "\n");
System.out.println("开始接收文件!" + "\n");

while (true) {
int read = 0;
if (inputStream != null) {
read = inputStream.read(buf);
}
passedlen += read;
if (read == -1) {
break;
}
//下面进度条本为图形界面的prograssBar做的,这里如果是打文件,可能会重复打印出一些相同的百分比
System.out.println("文件接收了" + (passedlen * 100/ len) + "%\n");
fileOut.write(buf, 0, read);
}
System.out.println("接收完成,文件存为" + savePath + "\n");

fileOut.close();
} catch (Exception e) {
System.out.println("接收消息错误" + "\n");
return;
}
}

public static void main(String arg[]) {
new ClientTest();
}
}



--------------------------------------------------------------------------------------------------------------------------------------------------------------------
http://topic.csdn.net/t/20060924/11/5044008.html


功能实现:两个Socket建立连接后,
server 发送,client 接收。
然后server向client发送图片,第一张可以正常接受,第二张就不行了。


代码: 
//ser.java
import com.sun.image.codec.jpeg.*;
import java.io.*;
import javax.imageio.*;
import java.awt.image.*;
import java.net.*;
import java.awt.*;

public class Ser extends Thread {

public Ser() {
}

public void run () {

try {

output = new ByteArrayOutputStream();
ss = new ServerSocket(2222);
s = ss.accept();
os = s.getOutputStream();

bi = ImageIO.read(new File( "k08.jpg "));
param = JPEGCodec.getDefaultJPEGEncodeParam(bi);
encoder = JPEGCodec.createJPEGEncoder(output, param);
encoder.encode(bi);
output.writeTo(os);
os.flush();
output.flush();


Thread.sleep(1000);
bi = ImageIO.read(new File( "k09.jpg "));
param = JPEGCodec.getDefaultJPEGEncodeParam(bi);
encoder = JPEGCodec.createJPEGEncoder(output, param);
encoder.encode(bi);
output.writeTo(os);
os.flush();
output.flush();

System.out.println( "Server thread start. ");
}
catch (Exception ex) {
ex.printStackTrace();
}

try {

os.close();
encoder.getOutputStream().close();
}
catch (Exception ex) {
ex.printStackTrace();
}

}

public static void main(String[] args) throws Exception {

new Ser().start();
}

private BufferedImage bi = null;
private ServerSocket ss = null;
private Socket s = null;
private OutputStream os = null;
private ByteArrayOutputStream output = null;
private JPEGEncodeParam param = null;
private JPEGImageEncoder encoder = null;
}


//Cli.java
import com.sun.image.codec.jpeg.*;
import java.io.*;
import javax.imageio.*;
import java.awt.image.*;
import java.net.*;
import java.awt.*;
import javax.swing.*;

class MyFrame extends JFrame {
private MyPanel panel = null;
public MyFrame() {
panel = new MyPanel();
add(panel);
}

public void drawScr(BufferedImage bi) {
panel.draw(bi);
}

private class MyPanel extends JPanel {

protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(bi, 0, 0, null);
}

public void draw(BufferedImage bi) {
this.bi = bi;
this.updateUI();
}

private BufferedImage bi = null;
}
}

public class Cli extends Thread {

public Cli() {
try {
//ip = InetAddress.getByName( "10.100.101.36 ");
ip = InetAddress.getLocalHost();
s = new Socket(ip, 2222);
is = s.getInputStream();
}
catch (Exception ex) {
ex.printStackTrace();
System.err.println( "public Client. ");
}
}

public void run() {
frame = new MyFrame();
frame.setSize(500, 300);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

try {


JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(is);
BufferedImage bi = decoder.decodeAsBufferedImage();
if (bi != null) {

frame.drawScr(bi);
System.out.println( "drawScr. ");
}


Thread.sleep(3000);
decoder = JPEGCodec.createJPEGDecoder(is);
bi = decoder.decodeAsBufferedImage();
if (bi != null) {

frame.drawScr(bi);
System.out.println( "drawScr. ");
}
}
catch (Exception ex) {
ex.printStackTrace();
}

}

public static void main(String[] args) throws Exception {
new Cli().start();
}

private InetAddress ip = null;
private Socket s = null;
private InputStream is = null;
private MyFrame frame = null;
}



-------------------------------------------------------------------------------------------------------------------------------------------------------------------

http://xiaoliefengfeng.iteye.com/blog/989799

android客服端上传图片到服务器,使用的xml来传输base64编码后的图片
我使用的是android自带的httpclient来发送post请求的,我也想过自己使用post方式来发送数据,但是,数据在服务器端进行base64解码的时候保存,我也没找出原因,所以就没写出来了
发送post请求就是因为post允许一次传输的数据量大,因为图片经过base64编码后,数据量大,如果采用get或者其他的方式来传输数据,传输效率不过,而且数据量大小受到限制


1.获取android客服端图片
  //对文件的操作
FileInputStream in = new FileInputStream(Environment.getExternalStorageDirectory() + "/images/musicmax.png");
byte buffer[] = StreamUtil.read(in);//把图片文件流转成byte数组
byte[] encod = Base64.encode(buffer,Base64.DEFAULT);//使用base64编码



2.发送post请求,注意android客服端访问网络记得要加访问网络的权限
 String path ="http://192.168.1.173:7999/videonews/TestServlet"; 
Map<String, String> params = new HashMap<String, String>();//定义一个保存key-value的Map用于保存需要传输的数据

params.put("value", new String(encod));//保存数据到map对象
Log.i(TAG,new String(encod));
if(StreamUtil.sendHttpClientPOSTRequest(path, params, "utf-8")){//使用帮助类来发送HttpClient来发送post请求
Log.i(TAG, "success :" + path + "----:decode:----" + new String(Base64.decode(encod, Base64.DEFAULT)));
}



服务器端的代码
String value = request.getParameter("value");//获取value的值
FileOutputStream fileout = new FileOutputStream("c:/music.png");//设置文件保存在服务器的什么位置
fileout.write(com.sun.org.apache.xml.internal.security.utils.Base64.decode(value.getBytes()));//使用base64解码
fileout.close();



StreamUtil帮助类里面完整代码
public class StreamUtil {
/**
* 返回字节数组
*
* @param in输入的流
* @return
* @throws Exception
*/

public static byte[] read(InputStream in) throws Exception {
ByteArrayOutputStream out = new ByteArrayOutputStream();
if (in != null) {
byte[] buffer = new byte[1024];
int length = 0;
while ((length = in.read(buffer)) != -1) {
out.write(buffer, 0, length);
}
out.close();
in.close();
return out.toByteArray();
}
return null;
}

/**
* 采用HttpClient发送POST请求
* @param path 请求路径
* @param params 请求参数
* @throws Exception
*/
public static boolean sendHttpClientPOSTRequest(String path, Map<String, String> params, String encoding) throws Exception{
List<NameValuePair> param = new ArrayList<NameValuePair>();
if(params!=null && !params.isEmpty()){
for(Map.Entry<String, String> entry : params.entrySet()){
param.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
}
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(param, encoding);
HttpPost post = new HttpPost(path);
// HttpGet get = new HttpGet();
post.setEntity(entity);
DefaultHttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(post);
if(response.getStatusLine().getStatusCode() == 200){
// response.getEntity().getContent();//获取服务器返回的数据
return true;
}
return false;
}
}



关于自己写post请求的代码,这个代码我测试过,在服务器对传输过来的数据进行base64解码的时候总报错,具体的原因我也没找出来,下面我贴出来代码,希望朋友们帮我找找原因
/*//对文件的操作  注:此方法测试有问题
FileInputStream in = new FileInputStream(Environment.getExternalStorageDirectory() + "/images/musicmax.png");
byte buffer[] = StreamUtil.read(in);
byte[] encod = Base64.encode(buffer,Base64.DEFAULT);

StringBuffer sb = new StringBuffer("value=");
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();

conn.setConnectTimeout(5 * 1000);
conn.setRequestMethod("POST");
conn.setDoOutput(true);//允许对外输出数据
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", (sb.toString().getBytes().length + encod.length) + "");
OutputStream outs = conn.getOutputStream();
outs.write(sb.toString().getBytes());
outs.write(encod);
outs.close();
Log.i(TAG,new String(encod));
if(conn.getResponseCode() == 200){
Log.i(TAG, "success :" + path + "----:decode:----" + new String(Base64.decode(encod, Base64.DEFAULT)));
//下面的代码是测试是否解码后能生成对应的图片没
// FileOutputStream fileout = new FileOutputStream(Environment.getExternalStorageDirectory() + "/images/musicmax1.png");
// fileout.write(Base64.decode(encod, Base64.DEFAULT));
// fileout.close();
}



====================================================================================================================================================================
通信:client发送请求到server,server返回结果。

client:


package client;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

public class client {
private static Socket socket;
private static String ServerIP = "localhost";
private static int ServerPort = 51707;
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
socket = new Socket(ServerIP,ServerPort);
//发送
ObjectOutputStream oos = new ObjectOutputStream(socket
.getOutputStream());
String s = "{\"head\":\"this is head\",\"body\":\"hello,你好吗?\"}";
oos.writeObject(s);
oos.flush();
//接收
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
String sers = "null";
try {
sers = (String)ois.readObject();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("serversay:"+sers);
// socket.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}




server:


package server;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Server implements Runnable {
public static final String SERVERIP = "localhost";
public static final int SERVERPORT = 51707;
private ServerSocket serverSocket;
private BufferedReader reader;
private Socket socket;
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("running...");
try {
serverSocket = new ServerSocket(SERVERPORT);
while(true){
Socket socket = serverSocket.accept();

ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
String s = "null";
try {
s = (String)ois.readObject();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(System.currentTimeMillis()+s);
ObjectOutputStream oos = new ObjectOutputStream(socket
.getOutputStream());
String ss = "{\"head\":\"this is head\",\"body\":\"hello,还可以\"}";
oos.writeObject(ss);
oos.flush();
socket.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("main...");
Server s = new Server();
s.run();
}

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值