TCP简介
TCP协议是一种处于传输层的协议,主要是通过用户之间的交互并相互确认来建立连接并实现数据传输的。
实现代码:
Client类
public class TcpClient {
public static void main(String[] args) {
Socket socket = null;
OutputStream out = null;
try {
//获取服务端ip和端口
InetAddress ip = InetAddress.getByName("127.0.0.1");
int port = 9999;
//创建连接用于发送信息
socket = new Socket(ip, port);
//获取一个输出流并输出消息
out = socket.getOutputStream();
out.write("Hello World".getBytes());
} catch (Exception e) {
e.printStackTrace();
}finally {
if(out!=null){
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(socket!=null){
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
Server类
public class TcpServer {
public static void main(String[] args) {
ServerSocket serversocket = null;
Socket socket = null;
InputStream in = null;
ByteArrayOutputStream baos = null;
try {
//创建连接用于接收信息
serversocket = new ServerSocket(9999);
socket = serversocket.accept();
//获取一个输入流获取信息
in = socket.getInputStream();
//创建一个管道流
baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
//将得到的数据写入管道流并输出
while((len=in.read(buffer))!=-1){
baos.write(buffer,0,len);
}
System.out.println(baos.toString());
} catch (IOException e) {
e.printStackTrace();
}finally {
if(baos!=null){
try {
baos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(in!=null){
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(socket!=null){
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(serversocket!=null){
try {
serversocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}