TCP聊天
TCP类型网络编程也是套接字编程
项目思路
- 客户端向服务端发送消息:客户端需要IP地址和端口号,用输出流输出消息.
- 服务端监听消息:需要监听一个端口,输入流接收消息时用管道流包装一下
传统IO流接收消息时可能存在的中文乱码问题
- 传统的IO流如果数组最后存储汉字时,空间不够了.
- 就会出现只存储一半汉字,乱码现象
优先处理异常,大型项目中会省很多事
客户端
package com.li.changGe.toChatWith;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
/**
* TCP聊天就是"套接字编程"
*
* 有个Scoket对象用输出流向服务端发送了一条消息
*/
public class Client {
public static void main(String[] args) {
new Client().send();
}
private OutputStream outputStream;
private Socket socket;
public void send(){
try{
InetAddress inetAddress = InetAddress.getByName("127.0.0.1");
//这个端口表示你要去往的地方的端口号是多少
int port = 9999;
socket = new Socket(inetAddress,port);
outputStream = socket.getOutputStream();
outputStream.write("Hello World".getBytes(StandardCharsets.UTF_8));
}catch (Exception e){
System.out.println("请检查ip地址或端口号");
}finally{
if(outputStream != null){
try {
outputStream.close();
}catch (Exception e){
System.out.println("检查输出流是否正确");
}
}
if(socket != null){
try {
socket.close();
}catch (Exception e){
System.out.println("请检查ip地址或端口号");
}
}
}//finally
}
}
服务端
package com.li.changGe.toChatWith;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Service {
public static void main(String[] args) {
/**
* 先运行服务端,再运行客户端
* 没有女朋友(服务端),你(客户端)给谁发信息
*/
new Service().takeOver();
}
private ByteArrayOutputStream byteArrayOutputStream;
private InputStream inputStream;
private Socket socket;
private ServerSocket serverSocket;
public void takeOver(){
try {
serverSocket = new ServerSocket(9999);
while (true){
//accept()阻塞接收:不收到别人发过来的信息不往下走代码
socket = serverSocket.accept();
//接收过来的信息被保存到这个流中了
inputStream = socket.getInputStream();
byteArrayOutputStream = new ByteArrayOutputStream();
byte[] bytes = new byte[1024];
int length;
while ((length = inputStream.read(bytes)) != -1){
//把接收到的信息写入到这个流中
byteArrayOutputStream.write(bytes,0,length);
//打印出这个流中的信息数据
System.out.println(byteArrayOutputStream.toString());
}
}//while(true)
}catch (Exception e){
System.out.println("请检查端口号是否正确");
}finally {
if(byteArrayOutputStream != null){
try {
byteArrayOutputStream.close();
}catch (Exception e){
System.out.println("字节输出流不正确");
}
}
if(inputStream != null){
try {
inputStream.close();
}catch (Exception e){
System.out.println("字节输入流不正确");
}
}
if(socket != null){
try {
socket.close();
}catch (Exception e){
System.out.println("检查端口号是否正确");
}
}
if(serverSocket != null){
try {
serverSocket.close();
}catch (Exception e){
System.out.println("端口号不正确");
}
}
}//finally
}
}
客户端(Client)发完信息后,服务端(Service)接收到信息:HelloWorld