【需求】:TCP上传图片
【代码一】:
/*
TCP发送图片D:\\WorkSpace\\测试.png
*/
import java.io.*;
import java.net.*;
//客户端
class PicClient
{
public static void main(String[] args) throws Exception
{
Socket s=new Socket("127.0.0.1",10006);
//读入图片
BufferedInputStream bis=new BufferedInputStream(new FileInputStream("D:\\WorkSpace\\测试.png"));
//输出口
BufferedOutputStream out=new BufferedOutputStream(s.getOutputStream());
//输入口
BufferedInputStream in=new BufferedInputStream(s.getInputStream());
int len=0;
byte[] buf=new byte[1024];
while((len=bis.read(buf))!=-1){
out.write(buf,0,len);
}
s.shutdownOutput();
byte[] bufIn=new byte[1024];
int num=in.read(bufIn);
System.out.println(new String(bufIn,0,num));
bis.close();
s.close();
}
}
//服务端
class PicServer
{
public static void main(String[] args) throws Exception
{
ServerSocket ss=new ServerSocket(10006);
Socket s=ss.accept();
String ip=s.getInetAddress().getHostAddress();
System.out.println(ip+"已连接...");
//输入口
BufferedInputStream in=new BufferedInputStream(s.getInputStream());
//输出口
BufferedOutputStream out=new BufferedOutputStream(s.getOutputStream());
//读入图片
BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream("D:\\WorkSpace\\网络编程\\test.png"));
int len=0;
byte[] buf=new byte[1024];
while((len=in.read(buf))!=-1){
bos.write(buf,0,len);
}
out.write("上传成功".getBytes());
out.flush();
//之前没有写flush(),客户端的int num=in.read(bufIn);输出为-1,就会报异常
bos.close();
s.close();
ss.close();
}
}
【截图一】:
【代码二】:
import java.io.*;
import java.net.*;
class PicClient2
{
public static void main(String[] args) throws Exception
{
Socket s=new Socket("127.0.0.1",10007);
FileInputStream fis=new FileInputStream("D:\\WorkSpace\\测试.png");
OutputStream out=s.getOutputStream();
InputStream in=s.getInputStream();
int len=0;
byte[] buf=new byte[1024];
while((len=fis.read(buf))!=-1){
out.write(buf,0,len);
}
s.shutdownOutput();
byte[] bufIn=new byte[1024];
int num=in.read(bufIn);
System.out.println(new String(bufIn,0,num));
fis.close();
s.close();
}
}
class PicServer2
{
public static void main(String[] args) throws Exception
{
ServerSocket ss=new ServerSocket(10007);
Socket s=ss.accept();
String ip=s.getInetAddress().getHostAddress();
System.out.println(ip+"is connected...");
InputStream in=s.getInputStream();
OutputStream out=s.getOutputStream();
FileOutputStream fos=new FileOutputStream("D:\\WorkSpace\\网络编程\\测试.png");
int len=0;
byte[] buf=new byte[1024];
while((len=in.read(buf))!=-1){
fos.write(buf,0,len);
}
out.write("上传成功".getBytes());
fos.close();
s.close();
ss.close();
}
}
【截图二】: