import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import org.junit.Test;
//TCP编程实例3,从客户端发送文件到服务器,服务器保存到本地,并返回发送成功给、客户端,并关闭相应的连接
public class TestTCP3 {
@Test
public void client() throws Exception{
//创建一个Socket的对象
Socket s = new Socket(InetAddress.getByName("127.0.0.1"),9898);
//从本地获取一个文件发送给服务端
OutputStream os = s.getOutputStream();
FileInputStream fis = new FileInputStream(new File("/Users/lixiuming/Desktop/商品详情图片/detail-1.jpg"));
byte[] b = new byte[1024];
int len;
while((len = fis.read(b))!=-1){
os.write(b,0,len);
}
s.shutdownOutput();
//接收来自服务端的消息
InputStream is = s.getInputStream();
byte[] b1 = new byte[1024];
int len1;
while((len1 = is.read(b1)) != -1){
String str = new String(b1,0,len1);
System.out.println(str);
}
//关闭相应的流和Socket
is.close();
os.close();
fis.close();
s.close();
}
@Test
public void server() throws Exception{
//创建一个ServerSocket
ServerSocket ss = new ServerSocket(9898);
//调用一个accept,返回一个socket对象
Socket s = ss.accept();
//将从客户端发送来的信息保存到本地
InputStream is = s.getInputStream();
FileOutputStream fos = new FileOutputStream(new File("2.jpg"));
byte[] b = new byte[1024];
int len;
while((len = is.read(b)) != -1){
fos.write(b, 0, len);
}
//“发送成功”的信息反馈给客户端
OutputStream os = s.getOutputStream();
os.write("发送成功".getBytes());
s.shutdownOutput();
//关闭相应的流和socket
os.close();
fos.close();
is.close();
s.close();
ss.close();
}
}
测试时注意:先看服务端,再开客户端