JAVASOCKET传输图片
服务器端: Java代码 收藏代码 import ; import ; import ; import ; import ; import ; import ; public class ServerTest { int port = 8821; void start() { Socket s = null; try { ServerSocket ss = new ServerSocket(port); while (true) { // 选择进行传输的文件 String filePath = “D:\\update\\image\\“; File fi = new File(filePath); (“文件长度:“ + (int) ()); // public Socket accept() throws // IOException侦听并接受到此套接字的连接。此方法在进行连接之前一直阻塞。 s = (); (“建立socket链接“); DataStream dis = new DataStream(new BufferedStream(())); (); DataStream fis = new DataStream(new BufferedStream(new FileStream(filePath))); DataOutputStream ps = new DataOutputStream(()); //将文件名及长度传给客户端。这里要真正适用所有平台,例如中文名的处理,还需要加工,具体可以参见Think In Java 4th里有现成的代码。 (()); (); ((long) ()); (); int bufferSize = 8192; byte[] buf = new byte[bufferSize]; while (true) { int read = 0; if (fis != null) { read = (buf); } if (read == -1) { break; } (buf, 0, read); } (); // 注意关闭socket链接哦,不然客户端会等待server的数据过来, // 直到socket超时,导致数据不完整。 (); (); (“文件传输完成“); } } catch (Exception e) { (); } } public static void main(String arg[]) { new ServerTest().start(); } } 具体实现: Java代码 收藏代码 package serverphoto; import .*; import .*; public class ClientSocket { private String ip; private int port; private Socket socket = null; DataOutputStream out = null; DataStream getMessageStream = null; public ClientSocket(String ip, int port) { = ip; = port; } public void CreateConnection() throws Exception { try { socket = new Socket(ip, port); } catch (Exception e) { (); if (socket != null) (); throw e; } finally { } } public void sendMessage(String sendMessage) throws Exception { try { out = new DataOutputStream(()); if ((“Windows“)) { (0 x1); (); return; } if ((“Unix“)) { (0 x2); (); return; } if ((“Linux“)) { (0 x3); (); } else { (sendMessage); (); } } catch (Exception e) { (); if (out != null) (); throw e; } finally { } } public DataStream getMessageStream() throws Exception { try { getMessageStream = new DataStream(new BufferedStream(())); return getMessageStream; } catch (Exception e) { (); if (getMessageStream != null) (); throw e; } finally { } } public void shutDownConnection() { try { if (out != null) (); if (getMessageStream != null) (); if (socket != null) (); } catch (Exception e) { } } } 客户端: Java代码 收藏代码 package serverphoto; import ; import ; import ; import ; 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) { (); } } private boolean createConnection() { cs = new ClientSocket(ip, port); try { (); (“连接服务器成功!“ + “\n“); return true; } catch (Exception e) { (“连接服务器失败!“ + “\n“); return false; } } private void sendMessage() { if (cs == null) return; try { (sendMessage); } catch (Exception e) { (“发送消息失败!“ + “\n“); } } private void getMessage() { if (cs == null) return; DataStream Stream = null; try { Stream = (); } catch (Exception e) { (“接收消息缓存错误\n“); return; } try { //本地保存路径,文件名会自动从服务器端继承而来。 String savePath = “D:\\update\“; int bufferSize = 8192; byte[] buf = new byte[bufferSize]; int passedlen = 0; long len=0; savePath += (); DataOutputStream fileOut = new DataOutputStream(new BufferedOutputStream(new BufferedOutputStream(new FileOutputStream(savePath)))); len = (); (“文件的长度为:“ + len + “\n“); (“开始接收文件!“ + “\n“); while (true) { int read = 0; if (Stream != null) { read = (buf); } passedlen += read; if (read == -1) { break; } //下面进度条本为图形界面的prograssBar做的,这里如果是打文件,可能会重复打印出一些相同的百分比 (“文件接收了“ + (passedlen * 100/ len) + “%\n“); (buf, 0, read); } (“接收完成,文件存为“ + savePath + “\n“); (); } catch (Exception e) { (“接收消息错误“ + “\n“); return; } } public static void main(String arg[]) { new ClientTest(); } } ——————————————————————————————————————————————————————– /t//11/.html 功能实现:两个Socket建立连接后, server 发送,client 接收。 然后server向client发送图片,第一张可以正常接受,第二张就不行了。 Java代码 收藏代码 代码: // import .*; import .*; import .*; import .*; import .*; import .*; public class Ser extends Thread { public Ser() { } public void run () { try { output = new ByteArrayOutputStream(); ss = new ServerSocket(2222); s = (); os = (); bi = (new File( “ “)); param = m(bi); encoder = (output, param); (bi); (os); (); (); (1000); bi = (new File( “ “)); param = m(bi); encoder = (output, param); (bi); (os); (); (); ( “Server thread start. “); } catch (Exception ex) { (); } try { (); ().close(); } catch (Exception ex) { (); } } 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; } // import .*; import .*; import .*; import .*; import .*; import .*; import .*; class MyFrame extends JFrame { private MyPanel panel = null; public MyFrame() { panel = new MyPanel(); add(panel); } public void drawScr(BufferedImage bi) { (bi); } private class MyPanel extends JPanel { protected void paintComponent(Graphics g) { (g); (bi, 0, 0, null); } public void draw(BufferedImage bi) { = bi; (); } private BufferedImage bi = null; } } public class Cli extends Thread { public Cli() { try { //ip = ( “ “); ip = (); s = new Socket(ip, 2222); is = (); } catch (Exception ex) { (); ( “public Client. “); } } public void run() { frame = new MyFrame(); (500, 300); (true); (); try { JPEGImageDecoder decoder = (is); BufferedImage bi = (); if (bi != null) { (bi); ( “drawScr. “); } (3000); decoder = (is); bi = (); if (bi != null) { (bi); ( “drawScr. “); } } catch (Exception ex) { (); } } public static void main(String[] args) throws Exception { new Cli().start(); } private InetAddress ip = null; private Socket s = null; private Stream is = null; private MyFrame frame = null; } ——————————————————————————————————————————————————————- /blog/989799 android客服端上传图片到服务器,使用的xml来传输编码后的图片 我使用的是android自带的httpclient来发送post请求的,我也想过自己使用post方式来发送数据,但是,数据在服务器端进行解码的时候保存,我也没找出原因,所以就没写出来了 发送post请求就是因为post允许一次传输的数据量大,因为图片经过编码后,数据量大,如果采用get或者其他的方式来传输数据,传输效率不过,而且数据量大小受到限制 1. 获取android客服端图片 Java代码 收藏代码 //对文件的操作 FileStream in = new FileStream(ory() + “/images/“); byte buffer[] = (in);//把图片文件流转成byte数组 byte[] encod = (buffer,);//使用编码 2. 发送post请求,注意android客服端访问网络记得要加访问网络的权限 Java代码 收藏代码 String path =“:7999/videonews/TestServlet“; Map params = new HashMap();//定义一个保存key-value的Map用于保存需要传输的数据 (“value“, new String(encod));//保存数据到map对象 (TAG,new String(encod)); if(t(path, params, “utf-8“)){//使用帮助类来发送HttpClient来发送post请求 (TAG, “success :“ + path + “—-:decode:—-“ + new String((encod, ))); } 服务器端的代码 JWww.bdlonGyUAN.cOm 输送带 ddava代码 收藏代码 String value = (“value“);//获取value的值 FileOutputStream fileout = new FileOutputStream(“c:/“);//设置文件保存在服务器的什么位置 ((()));//使用解码 (); StreamUtil帮助类里面完整代码 Java代码 收藏代码 public class StreamUtil { public static byte[] read(Stream in) throws Exception { ByteArrayOutputStream out = new ByteArrayOutputStream(); if (in != null) { byte[] buffer = new byte[1024]; int length = 0; while ((length = (buffer)) != -1) { (buffer, 0, length); } (); (); return (); } return null; } public static boolean sendHttpClientPOSTRequest(String path, Map params, String encoding) throws Exception{ List param = new ArrayList(); if(params!=null !()){ for( entry : ()){ (new BasicNamuePair((), ())); } } UrlEncodedEntity entity = new UrlEncodedEntity(param, encoding); HttpPost post = new HttpPost(path); // HttpGet get = new HttpGet(); (entity); DefaultHttpClient client = new DefaultHttpClient(); HttpResponse response = (post); if(().getStatusCode() == 200){ // ().getContent();//获取服务器返回的数据 return true; } return false; } } 关于自己写post请求的代码,这个代码我测试过,在服务器对传输过来的数据进行解码的时候总报错,具体的原因我也没找出来,下面我贴出来代码,希望朋友们帮我找找原因 Java代码 收藏代码 public static void main(String[] args) { // TODO Auto-generated stub try { socket = new Socket(ServerIP,ServerPort); //发送 ObjectOutputStream oos = new ObjectOutputStream(socket .getOutputStream()); String s = “{“head“:“this is head“,“body“:“hello,你好吗?“}“; (s); (); //接收 ObjectStream ois = new ObjectStream(()); String sers = “null“; try { sers = (String)(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block (); } (“serversay:“+sers); // (); } catch (UnknownHostException e) { // TODO Auto-generated catch block (); } catch (IOException e) { // TODO Auto-generated catch block (); } } } server: Java代码 收藏代码 package server; import ; import ; import ; import ; import ; import ; import ; import ; 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 stub (“running.“); try { serverSocket = new ServerSocket(SERVERPORT); while(true){ Socket socket = (); ObjectStream ois = new ObjectStream(()); String s = “null“; try { s = (String)(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block (); } (()+s); ObjectOutputStream oos = new ObjectOutputStream(socket .getOutputStream()); String ss = “{“head“:“this is head“,“body“:“hello,还可以“}“; (ss); (); (); } } catch (IOException e) { // TODO Auto-generated catch block (); } } public static void main(String[] args) { // TODO Auto-generated stub (“main.“); Server s = new Server(); (); } }
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/220622.html原文链接:https://javaforall.net
