UDP-Prim

Time: 2024-04-10 16:32:26
Author: Jackasher

UDP-Prim

现在我们可以利用UDP实现双向通信,创建两个线程类UDPReceive和UDPServer,然后让jack和flp启动线程即可,可以使用构造来传入参数,需要查看代码啊啊啊啊,可展开全文

UDPReceive:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package org.example;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;
import java.util.Scanner;

public class UDPReceive implements Runnable {

private DatagramSocket mySocket;
public String fromName;

public UDPReceive(int port,String fromName) throws SocketException {

mySocket = new DatagramSocket(port);
this.fromName = fromName;

}

@Override
public void run() {
System.out.println("Welcome to channel!");

while (true) {

int i = 0;
try {
//字节准备
byte[] bytes = new byte[1024*60];

//准备包接受数据
DatagramPacket packet = new DatagramPacket(bytes, 0, bytes.length);

//接受数据到packet
mySocket.receive(packet);

//获取接受数据
byte[] data = packet.getData();

//转化为字符串
String s = new String(data, 0, packet.getLength());

if (i ==0) {
System.out.println();
}
System.out.print(fromName + "(He/Her):" + s);

//关闭
// mySocket.close();
}catch (Exception e){
System.out.println(e);
}

}



}
}


UDPServer:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package org.example;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;
import java.util.Scanner;

//发送方演示
public class UDPServer implements Runnable {
private DatagramSocket mySocket;
// private int myPort;
private int toPort;
private String toIP;

private String myName;
// private DatagramPacket myPacket;


public UDPServer(int myPort, int toPort, String toIP, String myName) throws SocketException {
mySocket = new DatagramSocket(myPort);
this.toPort = toPort;
this.toIP = toIP;
this.myName = myName;
}

@Override
public void run() {
// System.out.print("Good Chat! input your msg here:");


while (true) {
try {

String msg;
Scanner scanner = new Scanner(System.in);
System.out.print( myName + "(Me):");
msg = scanner.nextLine();

byte[] bytes = new byte[1024 * 60];
bytes = msg.getBytes();
DatagramPacket sendPacket = new DatagramPacket(bytes, bytes.length, new InetSocketAddress(toIP, toPort));
mySocket.send(sendPacket);


} catch (IOException e) {
throw new RuntimeException(e);
}


}

}
}




UDP-Prim
http://example.com/2024/04/10/UDP-Prim/
作者
Jack Asher
发布于
2024年4月10日
许可协议