网络编程 TCP实现
TCP和UDP区别:TCP相当于打电话,双方需要同时在线连接,UDP相当于发邮件,一方发送,接收方不要求在线,在线即可接收发送方发送的消息
1. 编写发送方实体类 TcpSender(客户端)
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
public class TcpSender {
public static void main(String[] args) throws IOException {
// 服务器端的ip地址和端口
InetAddress inetAddress = InetAddress.getByName("127.0.0.1");
int port = 9999;
// 客户端发送接口
Socket socket = new Socket(inetAddress, port);
OutputStream outputStream = socket.getOutputStream();
outputStream.write("你好!".getBytes());
outputStream.close();
socket.close();
}
}
2. 编写接受方实体类 TcpReceive(服务器)
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class TcpReceive {
public static void main(String[] args) throws IOException {
// 服务器网络接收接口
ServerSocket serverSocket = new ServerSocket(9999);
// 接受发送方信息,进程阻塞状态
Socket accept = serverSocket.accept();
InputStream inputStream = accept.getInputStream();
int len;
byte[] bytes = new byte[1024];
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
while((len=inputStream.read(bytes)) != -1) {
byteArrayOutputStream.write(bytes, 0, len);
}
System.out.println(byteArrayOutputStream.toString());
inputStream.close();;
byteArrayOutputStream.close();
accept.close();
serverSocket.close();
}
}