Tcp客服端并发访问服务器

来源:互联网 发布:贵州省大数据 编辑:程序博客网 时间:2024/05/16 02:11

/*线程*/
 import java.net.*;
import java.io.*;

public class PicThread implements Runnable {
private Socket s;

public ClientThread(Socket ss) {

this.s = ss;
}

@Override
public void run() {
int count=1;
try{
String ip = s.getInetAddress().getHostAddress();
File file = new File("D:\\"+ip+"("+count+")"+".jpg");
while(file.exists()){
 
file = new File("D:\\"+ip+"("+(count++) +")"+".jpg");
}
InputStream in = s.getInputStream();
BufferedOutputStream buffin= 
new BufferedOutputStream(new FileOutputStream(file));
byte[] buf = new byte[1024];
int len = 0;
while((len = in.read(buf))!=-1){
buffin.write(buf, 0, len);
buffin.flush();
}
OutputStream out =s.getOutputStream();
byte[] info = "上传成功".getBytes();
out.write(info);
}catch(Exception e){
e.printStackTrace();
}
try {
s.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/*客服端*/
import java.io.*;
import java.net.*;
public class PicClient {

/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
//创建服务端点
Socket s = new Socket("127.0.0.1",10000);
// 读文件
BufferedInputStream buffin = new BufferedInputStream( new FileInputStream("D:\\3.jpg"));
OutputStream out = s.getOutputStream();
byte[] buf= new byte[1024];
int len =0;
// 往服务端写文件
while((len = buffin.read(buf))!=-1){
out.write(buf,0,len);
out.flush();
}
s.shutdownOutput();//告诉服务端 文件写完啦
// 接收服务端的反馈信息
InputStream in = s.getInputStream();
byte [] bfin = new byte[1024];
int lenIn = in.read(bfin);
System.out.println(new String(bfin,0,lenIn));
buffin.close();

}

}
/*服务器*/ 
import java.net.*;
import java.io.*;

public class PicServer {

/**
* @param args
* @throws Exception 
*/
public static void main(String[] args) throws Exception {
ServerSocket ss = new ServerSocket(10000);
while(true){
Socket socket=ss.accept();
new Thread(new ClientThread(socket)).start();
}
 

0 0
原创粉丝点击