您的位置:首页 > 理论基础 > 计算机网络

Tcp客服端并发访问服务器

2014-03-03 21:48 411 查看
/*线程*/

 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();

}
 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: