基于java UDP/TCP的在线聊天室
一、UDP
/**
* 发送接收不分离,只用一个DatagramSocket
*
*/
public class Machine{
private InetSocketAddress address;
private int machinePort;
public void setMachinePort(int machinePort){
this.machinePort=machinePort;
}
public void setDestinAddress(String hostName,int hostPort){
this.address=new InetSocketAddress(hostName, hostPort);
}
public void Running() throws Exception {
DatagramSocket socket = new DatagramSocket(machinePort);
//接收
new Thread(()->{
while (true) {
byte[] buff = new byte[1024];
DatagramPacket packet = new DatagramPacket(buff, 0, buff.length);
try {
socket.receive(packet);
} catch (IOException e) {
e.printStackTrace();
}
byte[] info = packet.getData();
String s = new String(info, 0, info.length);
System.out.println(s);
}
}).start();
//发送
new Thread(()->{
while (true) {
String info = new Scanner(System.in).next();
byte[] bytes = info.getBytes();
DatagramPacket packet = new DatagramPacket(bytes, 0, bytes.length, address);
try {
socket.send(packet);
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
}
二、TCP
public class TCPMachine {
private int receivePort;
private String destinHostName;
private Integer destinHostPort;
public void setReceivePort(int receivePort) {
this.receivePort = receivePort;
}
public void setDestinHostName(String destinHostName) {
this.destinHostName = destinHostName;
}
public void setDestinHostPort(Integer destinHostPort) {
this.destinHostPort = destinHostPort;
}
public void running() throws InterruptedException {
new Thread(() -> {
try {
ServerSocket socket = new ServerSocket(receivePort); //接收方
while (true) {
byte[] buff = new byte[1024 * 1024];
Socket accept = socket.accept();
InputStream is = accept.getInputStream();
int len = is.read(buff);
String info = new String(buff, 0, len);
System.out.println(info);
}
} catch (IOException e) {
e.printStackTrace();
}
}).start();
Thread.sleep(1000);
new Thread(() -> {
try {
while (true) {
Scanner scanner = new Scanner(System.in);
String info = scanner.next();
Socket socket = new Socket(destinHostName,destinHostPort);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
writer.write(info);
writer.flush();
writer.close();
socket.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}).start();
}
}