TCP服务器
- //1我得有一个IP和端口
- //2等待客户端连接过来
- //3读取客户端的消息
- //4管道流
- //5关闭资源
package Liu.FileDelivery;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
/**
* 服务器
*
* @author liu
*/
public class TcpServer {
public static void main(String[] args) throws IOException {
//1我得有一个IP和端口
ServerSocket serverSocket = new ServerSocket(9000);
//2等待客户端连接过来
Socket accept = serverSocket.accept();
//3读取客户端的消息
InputStream is = accept.getInputStream();
/* //输入文字,会乱码
int count = 0;
byte[] A=new byte[1];
while ((count = is.read(A)) != -1) {
System.out.println(new String(A,0,count));
}*/
//4管道流
FileOutputStream baos = new FileOutputStream(new File("G:\\文件.txt"));
int count = 0;
byte[] A = new byte[1];
while ((count = is.read(A)) != -1) {
baos.write(A, 0, count);
}
//5关闭资源
baos.close();
is.close();
accept.close();
serverSocket.close();
}
}
TCP客户端
- //1获取一个地址IP
- //2创建一个输出流
- //3读取文件
- //4写出文件
- //5高速服务器,已经写完
- //6关闭资源
package Liu.FileDelivery;
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
public class TcpClient {
public static void main(String[] args) throws IOException {
//1获取一个地址IP
Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 9000);
//2创建一个输出流
OutputStream os = socket.getOutputStream();
//3读取文件
FileInputStream fis = new FileInputStream("G:\\新建文本文档.txt");
//4写出文件
int count = 0;
byte[] buff = new byte[50];
while ((count = fis.read(buff)) != -1) {
os.write(buff);
}
//5高速服务器,已经写完
socket.shutdownOutput();
//6关闭资源
fis.close();
os.close();
socket.close();
}
}