网络编程之多人聊天
作者:互联网
package com.Network3;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Scanner;
/**
* 多线程多人聊天
* @author Next 2 You
*
*/
public class Socket_Packet {
public static void main(String[] args) {
new Send().start();
new Receive().start();
}
}
class Send extends Thread {
public void run() {
try {
String line;
Scanner input = new Scanner(System.in);
DatagramSocket socket = new DatagramSocket();
while (true) {
line = input.next();
if (line.equals("quit")) {
socket.close();
break;
}
byte[] byt = line.getBytes();
DatagramPacket packet = new DatagramPacket(byt, byt.length, InetAddress.getByName("192.168.3.238"),7778);
DatagramPacket packet2 = new DatagramPacket(byt, byt.length, InetAddress.getByName("192.168.3.224"),6666);
socket.send(packet);
socket.send(packet2);
}
} catch (SocketException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class Receive extends Thread {
public void run() {
try {
DatagramSocket socket = new DatagramSocket(6666);
while (true) {
DatagramPacket packet = new DatagramPacket(new byte[1024], 1024);
socket.receive(packet);
byte[] byt = packet.getData();
int len = packet.getLength();
if(packet.getAddress().getHostAddress().equals("192.168.3.238")){
System.out.println("小白:"+new String(byt, 0, len));
}else{
System.out.println("小明:"+new String(byt,0,len));
}
}
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
标签:DatagramPacket,java,之多人,byt,编程,packet,聊天,import,new 来源: https://blog.csdn.net/qq_33454111/article/details/100831813