allprojects {
repositories {
.
maven { url 'https://jitpack.io' }}
}
```
2. Add dependencies
```
dependencies {
implementation 'com.github.CWTakiku:NettyIM:latest'
}
```
### IV. Use
```
// Add network permissions
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
```
#### 1. Configure the client
So default can be replaced by the developer's implementation, as long as the corresponding interface is implemented
- Common configuration of multiple protocols
```
IMClient.Builder builder = new IMClient.Builder()
.setConnectTimeout(10, TimeUnit.SECONDS) // Set the connection timeout
.setResendCount(3)// Sets the number of retry attempts Whether
.setConnectRetryInterval(1000,TimeUnit.MILLISECONDS)/// set the connection retry time interval
.setConnectionRetryEnabled(true)// connection retry
.setSendTimeout(6,TimeUnit.SECONDS)// Sets the sending timeout
.setHeartIntervalBackground(30,TimeUnit.SECONDS)//heartbeat interval the background
.setReaderIdleTimeBackground(90,TimeUnit.SECONDS)//Background read idle trigger time,(Referring to not receiving any message from the server within a certain period of time, it is considered that the network is abnormal or the server is abnormal, if setReaderIdleReconnectEnabled(true) triggers reconnection)
.setEventListener(eventListener!=null?eventListener:new DefaultEventListener(userId)) // Event listener, optional
.setMsgTriggerReconnectEnabled(true) //Whether message sending triggers reconnection if the connection has been disconnected
.setReaderIdleReconnectEnabled(true) //Whether reading idle will trigger reconnection
.setProtocol(protocol) //What kind of protocol,IMProtocol.PRIVATE、IMProtocol.WEB_SOCKET、IMProtocol.UDP
.setOpenLog(true);//Whether to enable logs
```
- TCP configuration
```
if (protocol == IMProtocol.PRIVATE){ //The following two data formats are supported: protobuf and string
builder.setCodec(codecType == 0?new DefaultTcpProtobufCodec():new DefaultTcpStringCodec())//The default codec, developers can use their own protobuf or other codec formats
.setShakeHands(codecType == 0? new DefaultProtobufMessageShakeHandsHandler(getDefaultTcpHands()):new DefaultStringMessageShakeHandsHandler(getDefaultStringHands())) //Set handshake authentication. Optional
.setHeartBeatMsg(codecType == 0? getDefaultProtobufHeart(): getDefaultStringHeart()) //Setting the heartbeat is optional
.setAckConsumer(codecType == 0?new DefaultProtobufAckConsumer():new DefaultStringAckConsumer()) //Set the message confirmation mechanism
.registerMessageHandler(codecType == 0?new DefaultProtobufMessageReceiveHandler(onMessageArriveListener):new DefaultStringMessageReceiveHandler(onMessageArriveListener)) //Message receiving processor
.registerMessageHandler(codecType == 0?new DefaultReplyReceiveHandler(onReplyListener):new DefaultStringMessageReplyHandler(onReplyListener)) //Message status receiving processor
.registerMessageHandler(codecType == 0?new DefaultProtobufHeartbeatRespHandler():new DefaultStringHeartbeatRespHandler()) //Heartbeat receiving processor
.setTCPLengthFieldLength(2)//the length of the prepended length field. Only 1, 2, 3, 4, and 8 are allowed.
.addAddress(new Address(ip,9081,Address.Type.TCP))
.setFrameCodec(new DefaultLengthFieldBasedFrameCodec(2,65535));//Set up TCP packet loading and unpacking codecs
}
```
- WebSocket configuration
```
builder.setHeartBeatMsg(getDefaultWsHeart())
.setAckConsumer(new DefaultWSAckConsumer())
.registerMessageHandler(new DefaultWSMessageReceiveHandler(onMessageArriveListener))
.registerMessageHandler(new DefaultWSMessageReplyHandler(onReplyListener))
.registerMessageHandler(new DefaultWsHeartbeatRespHandler())
.addAddress(new Address(ip,8804,Address.Type.WS))
.setMaxFrameLength(65535*100)
// .addAddress(new Address(ip,8804,Address.Type.WSS))//The WSS protocol is supported. Add the wss identifier to scheme
.addWsHeader("user",userId); //webSocket specific and can be used for authentication
builder.setCodec(new DefaultUdpStringCodec(new InetSocketAddress(ip,8804), CharsetUtil.UTF_8)) //The default String codec, developers can set to their own format
.setShakeHands(new DefaultStringMessageShakeHandsHandler(getDefaultStringHands())) //Set handshake authentication. Optional
.setHeartBeatMsg(getDefaultStringHeart()) //Heartbeat receiving processor
.setAckConsumer(new DefaultStringAckConsumer()) // Set the message acknowledgement mechanism, which is required when message ACK is required
.registerMessageHandler(new DefaultStringMessageReceiveHandler(onMessageArriveListener)) //Message receiving processor
.registerMessageHandler(new DefaultStringMessageReplyHandler(onReplyListener))
.registerMessageHandler(new DefaultStringHeartbeatRespHandler())
.addAddress(new Address(ip, 8804, Address.Type.UDP));
```
#### 2. Construct the IMClient client
```
IMClient imClient = builder.build();
```
#### 3. Establish a connection
```
imClient.startConnect(); // Establish a connection
```
#### 4. Disconnect the connection
```
imClient.disConnect(); // The connection is disconnected actively and will not be reconnected automatically
```
#### 5. Send a message
```
Request request=new Request.Builder(). //Create a message sending request
setNeedACK(true).//If an ACK is required, true triggers the message acknowledgement mechanism
setSendRetry(true). //Can send retry
setBody(getMsgPack(appMessage.buildProto())). //body is the object supported by decoding
build();
```
```
imClient.newCall(request).enqueue(callback); // Send the message, the message in the sub thread callback
```
```
Disposable disposable= imClient.newCall(request).enqueue(callback).subscribe(consumer); // Sending messages subscribes to specific message processing. For example: I send a particular message and then want to subscribe to subsequent responses for that particular message
```
#### 6. Receive message
All message reception is registered in registerMessageHandler() in the above configuration. Developers can implement the MessageHandler interface themselves
public interface MessageHandler { boolean isFocusMsg(Object msg); //Is the type of message that the handler is concerned about void handleMsg(message message);//Receive processing message } ```
Status Listener In the setEventListener() configuration above, developers can inherit the EventListener class to listen for callbacks
/**
* connectStart
* @param inetSocketAddress
*/
public void connectStart( InetSocketAddress inetSocketAddress){
}
/**
* connectSuccess
*/
public void connectSuccess(){
}
/**
* connectionException
* @param throwable
*/
public void connectionException(Throwable throwable){
}
/**
* connectFailed
* @param inetSocketAddress
* @param ioe
*/
public void connectFailed( InetSocketAddress inetSocketAddress, IOException ioe) {
}
/**
* connectionBroken
*/
public void connectionBroken(){
}
/**
* connectionReleased
* @param connection
*/
public void connectionReleased(Connection connection) {
}
/**
* sendMsgStart
* @param call
*/
public void sendMsgStart(Call call) {
}
/**
* sendMsgEnd
* @param call
*/
public void sendMsgEnd(Call call) {
}
/**
* sendMsgFailed
* @param call
*/
public void sendMsgFailed(Call call){}
imClient.setBackground(background); // Set the front/background switch, and different heartbeat intervals will be automatically switched
imClient.isConnected(); // Check whether the connection is established
In TCP, FrameCodec packages and unpackages the TCP protocol. FrameCodec is unique to TCP, Codec is the encoding and decoding of the content. It supports both TCP and UDP protocols. ``` pipeline.addLast("frameEncoder", frameCodec.Encoder()); // out2 pipeline.addLast("frameDecoder", frameCodec.Decoder()); //in1
pipeline.addLast(codec.EnCoder().getClass().getSimpleName(),codec.EnCoder()); //out 1 pipeline.addLast(codec.DeCoder().getClass().getSimpleName(),codec.DeCoder()); //in2 ... ``` 1, the reception and processing of the data is in accordance with the above in1-->in2 sequence, the data is first unpacked, and then the real data is decoded. 2, the data is sent and processed according to the above out1-->out2 sequence, the real data is coded first, and then packaged.

Change localHost to the ip address of your computer in the IPConfig class, run the project, and run the APP on the mobile phone or simulator
APP module test contains the server demo, webscoket protocol, udp protocol and server demo of tcp protocol and string data formats. Run the corresponding server demo
Click the corresponding protocol in the APP to enter the chat interface
If you encounter any problems or questions in the use process, you are welcome to submit the issue, and welcome star! ** Contact information **QQ916379012
**Android IM feedback communication Group ** QQ group: 1051018406

$ claude mcp add NettyIM \
-- python -m otcore.mcp_server <graph>