/**
* 1、创建TCP服务端,TCP客户端
* 2、服务端等待客户端连接,客户端连接后,服务端向客户端写入图片
* 3、客户端收到后进行文件保存
* @author Administrator
*
*/
public class ServerTcpListener implements Runnable{ public static void main(String[] args) { try {
final ServerSocket server = new ServerSocket(33456); Thread th = new Thread(new Runnable() {
public void run() {
while (true) {
try {
System.out.println("开始监听...");
Socket socket = server.accept();
System.out.println("有链接");
send(socket);
} catch (Exception e) {
}
}
}
}); th.run(); //启动线程运行
} catch (Exception e) {
e.printStackTrace();
}
} @Override
public void run() { } public static void send(Socket socket) {
byte[] inputByte = null;
int length = 0;
DataOutputStream dos = null;
FileInputStream fis = null;
try {
try {
File file = new File("D:/1.png");
fis = new FileInputStream(file);
dos = new DataOutputStream(socket.getOutputStream()); inputByte = new byte[1024];
while ((length = fis.read(inputByte, 0, inputByte.length)) > 0) {
dos.write(inputByte, 0, length);
dos.flush();
} } finally {
if (fis != null)
fis.close();
if (dos != null)
dos.close();
if (socket != null)
socket.close();
}
} catch (Exception e) {
}
}
}
ServerTcpListener.java
public class ClientTcpReceive { public static void main(String[] args) { int length = 0;
byte[] receiveBytes = null;
Socket socket = null;
DataInputStream dis = null;
FileOutputStream fos = null; try {
try {
socket = new Socket("127.0.0.1", 33456); dis = new DataInputStream(socket.getInputStream());
fos = new FileOutputStream(new File("1.png")); receiveBytes = new byte[1024];
System.out.println("开始接收数据...");
while ((length = dis.read(receiveBytes, 0, receiveBytes.length)) > 0) {
System.out.println(length);
fos.write(receiveBytes, 0, length);
fos.flush();
}
System.out.println("完成接收");
} finally {
if (dis != null)
dis.close();
if (fos != null)
fos.close();
if (socket != null)
socket.close();
}
} catch (Exception e) {
e.printStackTrace();
}
} }
ClientTcpReceive.java