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

多线程在Socke与ServerSockett网络编程中的应用

2016-10-06 23:08 281 查看
Socket 客户端代码

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

/**
* Created by Administrator on 2016/10/6.
*/
public class PicClient {
public static void main(String[] args) throws Exception {
if (args.length!=1){
System.out.println("请选择JPG文件");
return;
}
File file =new File(args[0]);
Socket s = new Socket("192.168.0.103", 10005);
FileInputStream fis = new FileInputStream(file);
OutputStream out = s.getOutputStream();
byte[] buf = new byte[1024];
int len = 0;
while ((len = fis.read(buf))!=-1) {
out.write(buf, 0, len);
}
s.shutdownOutput();
InputStream is = s.getInputStream();
byte[] bufin = new byte[1024];
int num = is.read(bufin);
System.out.println(new String(bufin, 0, num));
fis.close();
s.close();

}
}

ServerSocket 服务端代码

import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
* Created by Administrator on 2016/10/6.
*/
public class PicServer {
public static void main(String[] args) throws Exception {
ServerSocket ss = new ServerSocket(10005);
Socket s = ss.accept();
System.out.println(s.getInetAddress().getHostAddress() + "连接中.....");
InputStream is = s.getInputStream();
FileOutputStream fos = new FileOutputStream("ceshi.jpg");
byte[] buf = new byte[1024];
int len = 0;
while ((len = is.read(buf)) != -1) {
fos.write(buf, 0, len);
//fos.flush();
}

OutputStream out = s.getOutputStream();
out.write("图片上传成功".getBytes());
System.out.println("....");
// out.flush();
// out.close();
fos.close();
ss.close();

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