网络编程-TCP-上传图片

要直接用到IO 、 先导包

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

public class Practice_1 {

    public static void main(String[] args) throws Exception   {
        // TODO Auto-generated method stub
        
        new Thread(new ClientDemo()).start();
        new Thread(new ServDemo()).start();
        
    }
}

class ClientDemo implements Runnable
{
    public void run()
    {
        try {
            method();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    public void method() throws Exception
    {
        Socket s = new Socket("199.234.8.31",10018);
        
        FileInputStream fis = new FileInputStream("pic_.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();
    }

}

class ServDemo implements Runnable
{

    public void run()
    {
        try {
            method();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
    public void method() throws Exception
    {
        ServerSocket ss = new ServerSocket(10018);
        Socket s = ss.accept();
        InputStream in = s.getInputStream();
        FileOutputStream fos = new FileOutputStream("pra.jpg");
        
        int len = 0;
        byte[] buf = new byte[1024];
        while( (len = in.read(buf))!=-1)
        {
            fos.write(buf,0,len);
        }
        
        
        OutputStream out = s.getOutputStream();
        out.write("上传成功".getBytes());
        
        ss.close();
        fos.close();
        
    }
}

class MyWant
{
    public void method() throws Exception
    {
        InetAddress i = InetAddress.getLocalHost();
        String ip = i.getHostAddress();
        String name = i.getHostName();
        System.out.println(ip+"...."+name);
        
    }
    
}

 

posted @ 2019-11-20 10:10  蚂蚁雅黑1010  阅读(170)  评论(0编辑  收藏  举报