什么是TCP(传输控制协议)?
传输控制协议(TCP,Transmission Control Protocol)是一种面向连接的、可靠的、基于字节流的传输层通信协议
而对于tcp网络聊天而言,首先我们需要先建立连接,只有在建立连接之后,我们才能够通过tcp进行数据传输。
客户端:
public class Client_work {
public static void main(String[] args) {
OutputStream outputStream=null;
Socket socket=null;
//1.我们客户端向服务端发送数据,首先需要知道服务端的ip和端口号
InetAddress byName=null;
try {
byName = InetAddress.getByName("127.0.0.1");
int port=9999;
//2.创建一个socket连接
socket = new Socket(byName,port);
//3.发送消息,通过io流
outputStream = socket.getOutputStream();
outputStream.write("mysql".getBytes());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
try {
outputStream.close();
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
服务端:
public class Server_work {
public static void main(String[] args) {
ServerSocket serverSocket=null;
InputStream inputStream=null;
Socket accept=null;
try {
//1.服务端需要有一个地址来接收数据
serverSocket = new ServerSocket(9999);
//2.等待客户端连接过来
accept = serverSocket.accept();
//3.把连接过来获取的socket数据进行读取
inputStream = accept.getInputStream();
//4.通过管道流把读取到的数据写出来
byte[] bs=new byte[1024];
int len;
while ((len=inputStream.read(bs))!=-1){
String s = new String(bs, 0, len);
System.out.println(s);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
try {
inputStream.close();
accept.close();
serverSocket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
服务端执行成功: