You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native TCP Socket客户端服务端IP配置及对接Java示例

React Native对接Java TCP服务端最小实现

服务端IP、端口配置直接传入TcpSocket.createConnection的第一个参数options对象中,对应字段为host(服务端IP)和port(服务端监听端口)。

完整可运行示例

以下代码可直接放入RN项目入口组件中运行,已适配你提供的Java服务端的DataInputStream/DataOutputStream编码规则:

import React, {useEffect} from 'react';
import {View, Button, Text} from 'react-native';
import TcpSocket from 'react-native-tcp-socket';

export default function TcpClientDemo() {
  let client = null;

  useEffect(() => {
    // 页面卸载时销毁连接避免内存泄漏
    return () => {
      client?.destroy();
    };
  }, []);

  const handleConnect = () => {
    // 连接配置项
    const connectOptions = {
      port: 8888, // 替换为你启动GreetingServer时传入的端口参数
      host: '192.168.1.102', // 替换为运行Java服务端设备的IP
      // 注意:安卓模拟器访问宿主机服务填10.0.2.2,iOS模拟器填127.0.0.1
      reuseAddress: true,
    };

    // 建立TCP连接
    client = TcpSocket.createConnection(connectOptions, () => {
      console.log('TCP连接已建立');
      // 适配Java Modified UTF-8编码规则:前2字节写入大端序的字符串字节长度
      const sendContent = 'Hello server!';
      const contentBuf = Buffer.from(sendContent, 'utf8');
      const lenBuf = Buffer.alloc(2);
      lenBuf.writeUInt16BE(contentBuf.length, 0);
      client.write(Buffer.concat([lenBuf, contentBuf]));
    });

    // 监听服务端返回消息
    client.on('data', (data) => {
      // 跳过前2位长度字节,转成可读字符串
      const receiveContent = data.slice(2).toString('utf8');
      console.log('收到服务端响应:', receiveContent);
      client.destroy();
    });

    // 监听错误
    client.on('error', (err) => {
      console.log('连接异常:', err);
    });

    // 监听连接关闭
    client.on('close', () => {
      console.log('连接已断开');
      client = null;
    });
  };

  return (
    <View style={{flex: 1, justifyContent: 'center', padding: 24}}>
      <Text style={{marginBottom: 16, textAlign: 'center'}}>TCP客户端测试</Text>
      <Button title="点击连接服务端发送消息" onPress={handleConnect} />
    </View>
  );
}

必要配置说明

  • 安卓端需在android/app/src/main/AndroidManifest.xml中添加网络权限:
<uses-permission android:name="android.permission.INTERNET" />
  • 真机调试时,手机和运行Java服务端的电脑需连接同一局域网,否则无法连通。
  • 如果你后续修改Java服务端改用普通字节流读写(不使用DataInputStream的readUTF方法),可以去掉编码适配逻辑,直接调用client.write('Hello server!')发送字符串即可。

内容的提问来源于stack exchange,提问作者Poorvaja

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.27 15:18:15