用线程改进TCP传输图片
因为一个服务器端要服务多个客户,一次只服务一个如果遇到网速慢的就没法玩了,所以我们这里选择用多线程来改进:
服务器端:
package net_study_12;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class UploadServer {
public static void main(String[] args) throws IOException {
ServerSocket ss =new ServerSocket(9797);
while(true){
Socket s =ss.accept();
new Thread(new ServerThread(s)).start();
}
}
}
服务器端的线程
package net_study_12;
import java.io.*;
import java.net.Socket;
public class ServerThread implements Runnable{
Socket s =new Socket();
public ServerThread(Socket s) {
this.s = s;
}
private ServerThread() {
}
@Override
public void run() {
try{
String name =System.currentTimeMillis()+".jpg";
BufferedInputStream bis =
new BufferedInputStream(s.getInputStream());
BufferedOutputStream bos =
new BufferedOutputStream(new FileOutputStream(name));
int len = 0;
byte[] byts = new byte[1024];
while ((len = bis.read(byts)) != -1) {
bos.write(byts, 0, len);
bos.flush();
}
OutputStream os = s.getOutputStream();
os.write("传输成功".getBytes());
s.close();
}catch (IOException e) {
e.printStackTrace();
}
}
}
客户端:
package net_study_12;
import java.io.*;
import java.net.Socket;
public class UploadClient {
public static void main(String[] args) throws IOException {
Socket s =new Socket("192.168.10.103",9797);
BufferedInputStream bis =
new BufferedInputStream(new FileInputStream("这是图片.jpg"));
BufferedOutputStream bos =
new BufferedOutputStream(s.getOutputStream());
byte[] byts =new byte[1024];
int len;
while((len=bis.read(byts))!=-1)
{
bos.write(byts,0,len);
bos.flush();
}
s.shutdownOutput();
InputStream is =s.getInputStream();
byte[] cbyts=new byte[1024];
int clen =is.read(cbyts);
System.out.println(new String(cbyts,0,clen));
}
}