黑马程序员技术交流社区
标题:
Tcp 服务端多线程
[打印本页]
作者:
fmi110
时间:
2015-10-7 17:19
标题:
Tcp 服务端多线程
Tcp协议传输文件时,传输完成一定要记得关闭输出流 new Socket().shutdownOutput();
以便将文件结尾标志传至服务器端,让程序正常终止。
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class TcpDemo4 {
/**
* TCP协议服务端多线程技术
* @throws Exception
*/
public static void main(String[] args) throws Exception {
ServerSocket ss = new ServerSocket(10888);
while(true){
Socket s = new Socket();
s = ss.accept();
new Thread(new Upload(s)).start();
}
}
}
class Client{
public static void main(String[] args) throws Exception, IOException {
Socket s = new Socket("192.168.220.1",10888);
File src = new File("F:\\深色壁纸\\1 (2).jpg");
FileInputStream fin = new FileInputStream(src);
byte[] buf = new byte[1024];
int len = 0;
OutputStream os = s.getOutputStream();
System.out.println("客户端开始传输...");
while ((len = fin.read(buf)) != -1) {
os.write(buf, 0, len);
}
s.shutdownOutput();
InputStream in = s.getInputStream();
len = in.read(buf);
System.out.println(new String(buf, 0, len));
fin.close();
s.close();
}
}
class Upload implements Runnable{
private Socket s;
private int count = 0;
public Upload(Socket s) {
super();
this.s = s;
}
@Override
public void run() {
System.out.println("服务器启动");
String ip = s.getInetAddress().getHostAddress();
File dir = new File("f:\\tcp多线程");
dir.mkdirs();
File des = new File(dir,ip+".jpg");
while (des.exists())
des = new File(dir, ip + "(" + ++count + ")" + ".jpg");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(des);
InputStream in = s.getInputStream();
byte[] buf = new byte[1024];
int len = 0;
System.out.println("开始上传...");
while ((len = in.read(buf)) != -1) {
fos.write(buf, 0, len);
}
System.out.println("done");
OutputStream os = s.getOutputStream();
os.write("上传成功".getBytes());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(null!=fos)
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2