1、利用TCP单线程从客户端将图片发送给服务端。
客户端:
import java.io.*;
import java.net.*;
public class TcpPicClient {
public static void main(String[] args) throws Exception{
Socket s = new Socket("10.101.76.80",10006);
FileInputStream fis = new FileInputStream("1.jpg");//选择要发送的图片
OutputStream out = s.getOutputStream();
byte[] buf = new byte[4096];
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();
}
}
服务端:
import java.io.*;
import java.net.*;
public class TcpPicServer {
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 + "......connected");
InputStream in = s.getInputStream();
FileOutputStream fos = new FileOutputStream("server.jpg");//保存的图片名
byte[] buf = new byte[4096