Java网络编程下
需求:客户端向服务端传送图片并存在在服务端。
public class PicServer {
public static void main(String[] args) throws IOException { ServerSocket ss = new ServerSocket(10007);
while (true) { Socket s = ss.accept(); InputStream in = s.getInputStream(); String ip = s.getInetAddress().getHostAddress();
FileOutputStream fos = new FileOutputStream(“server.jpg”);
byte[] buf = new byte[1024]; int len = 0; while ((len = in.read(buf))!= -1){ fos.write(buf, 0, len); }
java.io.OutputStream out = s.getOutputStream(); out.write("上传成功".getBytes()); fos.close(); s.close(); }
} } |
这个服务端有个局限性,当A客户端连接上以后,被服务端获取到,服务端执行具体流程。这时B客户端连接,只有等待。因为服务端还没有处理完A客户端的请求,还有循环回来执行下次accept方法,所以暂时获取不到B客户端对象。那么为了可以让多个客户端同时并发访问服务端那么服务端最好就是将每个客户端封装到一个单独的线程中,这样,
就可以同时处理多个可以用多线程实现并发上传图片。代码如下:
/** * 客户端 * 1、服务端点 * 2、读取客户端已有的图片数据 * 3、通过socket输出流将数据发给服务端 * 4、读取服务端反馈信息 * 5、关闭。 * @author Administrator * */ public class PicClient {
public static void main(String[] args) throws IOException { Socket s = new Socket("192.168.0.3",10007); FileInputStream fis = new FileInputStream("c:\\1.jpg"); OutputStream out = s.getOutputStream(); byte[] buf = new byte[1024]; int len = 0; while ((len = fis.read(buf)) != -1) { out.write(buf, 0, len); }
// 告诉服务端数据已写完 s.shutdownOutput();
InputStream in = s.getInputStream();
byte[] bufin = new byte[1024];
int num = in.read(bufin); System.out.println(new String(bufin, 0, num)); fis.close(); s.close(); } } |
/** * 服务端 * @author Administrator * */ public class PicServer {
public static void main(String[] args) throws IOException { ServerSocket ss = new ServerSocket(10007);
while (true) { Socket s = ss.accept();
//每一个新的连接来都起一个新的线程 new Thread(new PicThread(s)).start(); }
} }
class PicThread implements Runnable { private Socket s; PicThread(Socket s) { this.s = s; } @Override public void run() { // 记数器 int count = 1; try { InputStream in = s.getInputStream(); String ip = s.getInetAddress().getHostAddress(); File file = new File(ip + "(" + count + ")" + ".jpg");
while (file.exists()) file = new File(ip + "(" + (count++) + ")" + ".jpg");
FileOutputStream fos = new FileOutputStream(file);
byte[] buf = new byte[1024]; int len = 0; while ((len = in.read(buf))!= -1){ fos.write(buf, 0, len); }
java.io.OutputStream out = s.getOutputStream(); out.write("上传成功".getBytes()); fos.close(); s.close();
} catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
} |
用打印流实行最简单的服务器,让浏览器访问并返回一段数据:
public class BrowserServer {
public static void main(String[] args) throws IOException { ServerSocket ss = new ServerSocket(11000); Socket s = ss.accept(); String ip = s.getInetAddress().getHostAddress(); System.out.println(ip + "...connected");
PrintWriter out = new PrintWriter(s.getOutputStream(), true); //PrintStream out = new PrintStream(s.getOutputStream(), true); out.println("你好客户端!"); s.close(); ss.close(); } } |
---------------------完----------------------------