多线程在Socke与ServerSockett网络编程中的应用

来源:互联网 发布:美好的诗句 知乎 编辑:程序博客网 时间:2024/05/17 01:35

Socket 客户端代码

import java.io.File;import java.io.FileInputStream;import java.io.InputStream;import java.io.OutputStream;import java.net.Socket;/** * Created by Administrator on 2016/10/6. */public class PicClient {    public static void main(String[] args) throws Exception {        if (args.length!=1){            System.out.println("请选择JPG文件");            return;        }        File file =new File(args[0]);        Socket s = new Socket("192.168.0.103", 10005);        FileInputStream fis = new FileInputStream(file);        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 is = s.getInputStream();        byte[] bufin = new byte[1024];        int num = is.read(bufin);        System.out.println(new String(bufin, 0, num));        fis.close();        s.close();    }}
ServerSocket 服务端代码
import java.io.FileOutputStream;import java.io.InputStream;import java.io.OutputStream;import java.net.ServerSocket;import java.net.Socket;/** * Created by Administrator on 2016/10/6. */public class PicServer {    public static void main(String[] args) throws Exception {        ServerSocket ss = new ServerSocket(10005);        Socket s = ss.accept();        System.out.println(s.getInetAddress().getHostAddress() + "连接中.....");        InputStream is = s.getInputStream();        FileOutputStream fos = new FileOutputStream("ceshi.jpg");        byte[] buf = new byte[1024];        int len = 0;        while ((len = is.read(buf)) != -1) {            fos.write(buf, 0, len);            //fos.flush();        }        OutputStream out = s.getOutputStream();        out.write("图片上传成功".getBytes());        System.out.println("....");       // out.flush();       // out.close();        fos.close();        ss.close();    }}



0 0