多线程socket
实现接收方和发送方在同一个文件内
public class Demo_Socket {
public static void main(String[] args) throws IOException {
new SocketReceive().start();
new SocketSend().start();
}
}
/**
* socket 发送方
*
* @author JerichoPH
*/
class SocketSend extends Thread {
@Override
public void run() {
try {
Scanner sc = new Scanner(System.in); // 获取键盘输入流
DatagramSocket socket = new DatagramSocket(); // 创建socket对象
while (true) {
String line = sc.nextLine(); // 获取键盘录入
if ("quit".equals(line)) { // 如果输入quit则退出连接
break;
}
DatagramPacket packet = // 创建数据包对象
new DatagramPacket(line.getBytes(), line.getBytes().length, InetAddress.getByName("127.0.0.1"),
6666);
socket.send(packet); // 发送数据包
}
socket.close(); // 关闭socket对象
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* socket 接收方
*
* @author JerichoPH
*/
class SocketReceive extends Thread {
@Override
public void run() {
try {
DatagramSocket socket = new DatagramSocket(6666); // 创建socket连接
DatagramPacket packet = new DatagramPacket(new byte[1024], 1024);
while (true) {
socket.receive(packet); // 接收消息
byte[] arr = packet.getData(); // 提取数据
int len = packet.getLength(); // 获取有效字节个数
String ip = packet.getAddress().getHostAddress(); // 获取IP地址
int port = packet.getPort(); // 获取端口号
System.out.println(ip + ":" + port + ":" + new String(arr, 0, len));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
网友评论