气死了,这个错误搞了半天!
package Internet;
import java.net.DatagramSocket;
import java.net.SocketException;
public class Test11_Me {
public static void main(String[] args) throws Exception {
new Thread(new Test11_Send(205,"localhost",2000)).start();
new Thread(new Test11_Receive(2005,"哥哥")).start();
// 错了半天,才发现:这两个myPort 不能相同,2001 != 2005 ,气死了,调了半天
// Address already in use: bind 看出错的解释啊,混蛋
}
}
////////////////////////////////
package Internet;
import java.net.DatagramSocket;
import java.net.SocketException;
public class Test11_MyBrother {
public static void main(String[] args) throws Exception {
new Thread(new Test11_Send(200,"localhost",2005)).start();
new Thread(new Test11_Receive(2000,"弟弟")).start();
}
}
//////////////////////////
package Internet;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.*;
public class Test11_Send implements Runnable {
int myPort,toPort;
String toIP;
DatagramSocket socket=null;
BufferedReader reader =null;
public Test11_Send(int myPort,String toIP ,int toPort){
this.myPort = myPort;
this.toPort = toPort;
this.toIP = toIP;
try {
socket=new DatagramSocket(myPort);
reader = new BufferedReader(new InputStreamReader(System.in));
}catch (Exception e){
e.printStackTrace();
}
}
@Override
public void run() {
try {
// 2. 不断地建立包裹并发送出去: 可以不停地发消息
// 从控制台键盘读取信息,并且发送出去
while (true) {
String msg = reader.readLine();
// byte[] data=(byte[])reader; 这里不能强制转换
DatagramPacket packet = new DatagramPacket(msg.getBytes(), 0, msg.length(), new InetSocketAddress(toIP, toPort));
socket.send(packet);
if (msg.equals("bye")) {
break;
} // 结束判定
}
} catch (Exception e) {
e.printStackTrace();
}
// 3. 关闭
socket.close();
}
}
///////////////
package Internet;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
public class Test11_Receive implements Runnable{
int myPort,toPort;
DatagramSocket socket=null;
String str;
public Test11_Receive( int myPort,String str){
this.myPort = myPort;
this.str=str;
// 1. 创建自己的端口
try {
socket = new DatagramSocket(myPort);
} catch (SocketException e) {
throw new RuntimeException(e);
}
}
@Override
public void run() {
try {
// 2. 不停地接收包裹:可以不停地接收信息
while (true){
byte[] buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer,0,buffer.length);
socket.receive(packet); // 阻塞式接收:有就接收
String msg=new String(packet.getData(),0,packet.getLength());
System.out.println(str+":"+msg);
if (msg.equals("bye")){
break;
}
}
}catch (Exception e){
e.printStackTrace();
}
// 3. 关闭
socket.close(); // 阻塞式接收:不断地接收
}
}
标签:11,java,myPort,聊天,import,Test11,new,多线程,public
From: https://www.cnblogs.com/zhanjianhai/p/17690232.html