什么是TCP
TCP(Transmission Control Protocol 传输控制协议)是一种面向连接(连接导向)的、可靠的、 基于IP的传输层协议。TCP在IP报文的协议号是6。TCP是一个超级麻烦的协议,而它又是互联网的基础,也是每个程序员必备的基本功。
TCP简单的demo例子
//客户端
public class TCPClientDemo01 {
public static void main(String[] args) throws IOException {
Socket socket = null;
OutputStream outputStream = null;
try {
//需要一个IP
InetAddress inetAddress = InetAddress.getByName("127.0.0.1");
//创建一个socket连接
socket = new Socket(inetAddress,10000);
//发生消息 IO流
outputStream = socket.getOutputStream();
outputStream.write("你好,欢迎继续变强".getBytes());
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(outputStream != null)
outputStream.close();
if(socket != null)
socket.close();
}
}
}
//服务端
public class TcpServerDemo01 {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
Socket socket = null;
InputStream inputStream = null;
ByteArrayOutputStream byteArrayOutputStream = null;
try {
//1.我得有一个地址
serverSocket = new ServerSocket(10000);
while (true){
//等待客户端连接管来
socket = serverSocket.accept();
inputStream = socket.getInputStream();
//管道流
byteArrayOutputStream = new ByteArrayOutputStream();
byte [] buffer = new byte[1024];
int len;
while ((len = inputStream.read(buffer)) != -1) {
byteArrayOutputStream.write(buffer,0,len);
}
System.out.println(byteArrayOutputStream.toString());
}
} catch (IOException e) {
e.printStackTrace();
}finally {
if(byteArrayOutputStream != null)
byteArrayOutputStream.close();
if(inputStream != null)
inputStream.close();
if(socket != null)
socket.close();
if(serverSocket != null)
serverSocket.close();
}
}
}