//设置socket
val socket = DatagramSocket()
val serverPort = 9000
val address = InetAddress.getByName("ip地址")
//发送
val bytes = message.toByteArray(Charsets.UTF_8)
val len = bytes.size
val sendPacket = DatagramPacket(bytes, len, address, serverPort)
socket.send(sendPacket)
//接收
socket.receive(receivePacket)
val data = String(receivePacket.data, Charsets.UTF_8)
//处理接收到的数据
//关闭连接
socket.close()
TCP客户端通信
我们在使用TCP客户端通信方式时,我们会这样实现
//设置socket
val serverPort = 9000
val address = InetAddress.getByName("ip地址")
val socket = Socket(address, serverPort)
val input = socket.getInputStream()
val output = socket.getOutputStream()
//发送
output.write(message.toByteArray(Charsets.UTF_8))
//接收
val len = input.read(receive)
val data = String(receive, 0, len, Charsets.UTF_8)
//处理接收到的数据
//关闭连接
socket.close()