我想建立一个TCP套接字连接。
my server code in java.
// File Name GreetingServer.java
import java.net.*;
import java.io.*;
public class GreetingServer extends Thread {
private ServerSocket serverSocket;
public GreetingServer(int port) throws IOException {
serverSocket = new ServerSocket(port);
serverSocket.setSoTimeout(10000);
}
public void run() {
while(true) {
try {
System.out.println("Waiting for client on port " +
serverSocket.getLocalPort() + "...");
Socket server = serverSocket.accept();
System.out.println("Just connected to " + server.getRemoteSocketAddress());
DataInputStream in = new DataInputStream(server.getInputStream());
System.out.println(in.readUTF());
DataOutputStream out = new DataOutputStream(server.getOutputStream());
out.writeUTF("Thank you for connecting to " + server.getLocalSocketAddress()
+ "nGoodbye!");
server.close();
} catch (SocketTimeoutException s) {
System.out.println("Socket timed out!");
break;
} catch (IOException e) {
e.printStackTrace();
break;
}
}
}
public static void main(String [] args) {
int port = Integer.parseInt(args[0]);
try {
Thread t = new GreetingServer(port);
t.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
我想做一个客户端在react-native .
导入库:
import TcpSocket from 'react-native-tcp-socket';
// const net = require('react-native-tcp-socket');
// Create socket
const client = TcpSocket.createConnection(options, () => {
// Write on the socket
client.write('Hello server!');
// Close socket
client.destroy();
});
client.on('data', function(data) {
console.log('message was received', data);
});
client.on('error', function(error) {
console.log(error);
});
client.on('close', function(){
console.log('Connection closed!');
});
我在这里引用了上面的代码
但是,我需要更多的信息。
我在客户端哪里可以提供服务器的IP地址?
我需要一个小的例子,TCP客户端在react-native。
似乎您需要在host字段的选项对象中指定IP,如react-native-tcp-socket文档中所述。
host - socket应该连接的主机。IPv4格式的IP地址或'localhost'。默认值:"localhost"。
例如:
const options = {
port: 8443,
host: "example.com", //give your IP address
tls: true,
};
// Create socket
const client = TcpSocket.createConnection(options, () => {
// Write on the socket
client.write('Hello server!');
// Close socket
client.destroy();
});