1、TCP特点
Transmission Control Protocol 传输控制协议
面向连接,通过三次握手建立连接,可靠的协议
有明确的客户端和服务器端
一旦连接可以将数据当做一个双向字节流进行交换,开销大
2、相关类
Socket | 客户端Socket服务类 |
ServerSocket | 服务器端Socket服务类 |
3、TCP传输示例代码
// 客户端
public class Client {
public static void main(String[] args) throws IOException {
// 1:使用Socket对象,创建客户端Socket服务
Socket socket = new Socket("127.0.0.1", 20000);
// 2:通过连接建立数据传输通道,通过Socket对象可以获得通道中的输入输出流对象
OutputStream out = socket.getOutputStream();
InputStream in = socket.getInputStream();
// 3:使用输入输出流,读写数据
out.write("Hello World".getBytes());
byte[] b = new byte[1024];
int length = in.read(b);
String message = new String(b, 0, length);
System.out.println(message);
// 4:关闭Socket服务
socket.close();
}
}
// 服务器端
public class Server {
public static void main(String[] args) throws IOException {
// 1:通过ServerSocket对象,创建服务器端Socket服务,必须设置端口号
ServerSocket server = new ServerSocket(20000);
// 2:获取连接的客户端的Socket对象,accept是阻塞方法
Socket socket = server.accept();
// 3:通过Socket对象获得输入输出流进行读写数据
InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();
byte[] b = new byte[1024];
int length = in.read(b);
String message = new String(b, 0, length);
System.out.println(message);
out.write("收到".getBytes());
// 4:关闭客户端、服务器端的服务
socket.close();
server.close();
}
}
注意,阻塞式方法需要结束标记,否则容易造成双方同时等待可以通过Socket.shutdownInput(),Socket.shutdownOutput()通知对方.
4、实现文件上传
// 客户端
public class UploadClient {
public static void main(String[] args) throws Exception {
// 建立Socket服务
Socket socket = new Socket("192.168.1.100", 20000);
// 建立文件及流对象
File file = new File("src/com/net/upload/a.jpg");
FileInputStream fis = new FileInputStream(file);
OutputStream out = socket.getOutputStream();
// 通过流上传文件
byte[] bur = new byte[1024];
int length = 0;
while ((length = fis.read(bur)) != -1) {
out.write(bur, 0, length);
}
fis.close();
// 发送完毕,关闭Socket的输出流
socket.shutdownOutput();
// 接收结束信息
InputStream in = socket.getInputStream();
byte[] message = new byte[1024];
length = in.read(message);
System.out.println(new String(message, 0, length));
// 关闭Socket服务
socket.close();
}
}
// 服务器端
public class UploadServer {
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(20000);
while (true) {
Socket socket = server.accept();
new Thread(new Upload(socket)).start();
}
}
}
// 上传任务类
class Upload implements Runnable {
private Socket socket;
public Upload(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
try {
String ip = socket.getInetAddress().getHostAddress();
// 建立文件及流对象
InputStream in = socket.getInputStream();
File file = new File("src/com/net/upload/" + ip + "a.jpg");
FileOutputStream fos = new FileOutputStream(file);
// 接收文件
byte[] bur = new byte[1024];
int length = 0;
while ((length = in.read(bur)) != -1) {
fos.write(bur, 0, length);
}
fos.close();
// 向客户端返回上传完毕消息
OutputStream out = socket.getOutputStream();
out.write("上传完毕".getBytes());
// 关闭Socket服务
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}