发送数据包用的方法是: DatagramSocket.send(DatagramPacket p)
接收数据包用的方法是: DatagramSocket.receive(DatagramPacket p)
// 服务端
fun main(){
// 创建服务器端,注册端口
val socket = DatagramSocket(3333)
// 创建数据包接收客户端
val buf = ByteArray(1024*64)
val packet = DatagramPacket(buf, buf.size)
// 接收客户端数据
thread {
while (true){
try {
socket.receive(packet)
} catch (e: Exception) {
e.printStackTrace()
}
val len = packet.length
val rs = String(buf,0,len)
println("收到ip为:${packet.address} 端口为:${packet.port} 消息:$rs")
}
}
// 向客户端发数据
var address :InetAddress?=null
var port = 0
var flag = false
thread {
while (true) {
if (!flag) {
// 定义客户端的地址、端口号、数据
address = packet.address //获取发送端的地址
port = packet.port //获取 发送端进程所绑定的端口
flag = true
}
println("请输入:")
val scanner = Scanner(System.`in`)
val msg = scanner.nextLine()
val buffer = msg.toByteArray()
val packets = DatagramPacket(buffer, buffer.size, address, port)
try {
socket.send(packets)
} catch (e: IOException) {
e.printStackTrace()
}
}
}
}
/*
服务端启动成功
(客户端输入信息后,服务端接收)
收到ip为:/127.0.0.1 端口为:2222 消息:hello server
(服务端此时输入,ok)
*/
// 接收端
fun mian(){
// 定义服务器的地址、端口号、数据
val address = InetAddress.getByName("localhost")
val port = 3333
// 创建发送端对象:发送端自带默认端口号
val socket = DatagramSocket(2222)
println("客户端启动成功")
// 向服务端发送信息
thread {
try {
while (true) {
println("请输入:")
val sc = Scanner(System.`in`)
val msg = sc.nextLine()
val buffer = msg.toByteArray()
val packets = DatagramPacket(buffer, buffer.size, address, port)
socket.send(packets)
}
} catch (e: Exception) {
e.printStackTrace()
}
}
// 通过循环不停的向服务器接收数据
thread {
try {
while (true) {
val buf = ByteArray(1024 * 64)
val packet = DatagramPacket(buf, buf.size)
socket.receive(packet)
val len = packet.length
val rs = String(buf, 0, len)
println("收到了ip为:" + packet.address.toString() + " 端口号为:" + packet.port.toString() + "的消息:" + rs)
}
} catch (e: Exception) {
e.printStackTrace()
}
}
}
/*
客户端启动成功
请输入:
hello server
(服务端输入消息后)
收到了ip为:/127.0.0.1 端口号为:3333的消息:ok
*/