public void run(){
try{
while(true){
//创建一个接收包
byte[] bys = new byte[1024];
DatagramPacket dp = new DatagramPacket(bys,bys.length);
//接收数据
ds.receive(dp);
//解析数据
String IP = dp.getAddress().getHostAddress();
String str = new String(dp.getDate(),0,dp.getLength());
System.out.println(IP + " : " + str);
}
}catch(IOException e){
e.printStackTrace();
}
}
}
聊天室:
public class ChatRoom{
public static void main(String[] args) throws IOException{
//创建发送端和接收端的Socket对象
DatagramSocket dsSend = new DatagramSocket();
DategramSocket dsReceive = new DatagramSocket(12345);
//创建发送端和接收端的资源对象
SendThread st = new SendThread(dsSend);
ReceiveThread rt = new ReceiveThread(dsReceive);
//创建线程
Thread t1 = new Thread(st);
Thread t2 = new Thread(rt);
//开启线程
t1.start();
t2.start();
}
}
3.TCP
A:最基本的TCP协议发送和接收数据
客户端:
public static ClientDemo{
public static void main(String[] args) throws IOException{
//创建客户端Socket对象
Socket s = new Socket("192.168.1.124",8888);
//创建输出流,写数据
OutputStream os = s.getOutputStream();
os.write("hello,TCP,我来了!".getBytes());
//释放资源
s.close();
}
}
服务器端:
public class ServerDemo{
public static void main(String[] args) throws IOException{
//创建服务器端Socket对象
ServerSocket ss = new ServerSocket(8888);
//监听客户端连接,返回一个Socket对象
Socket s = ss.accept();
//创建输入流,读取数据并显示在控制台
InputStream is = s.getInputStream();
byte[] bys = new byte[1024];
int len = is.read(bys);
String str = new String(bys,0,len);
String IP = s.getInetAddress().getHostAddress();
System.out.println(IP + " : " + str);
//释放资源
s.close();
}
}
B:服务器端给出反馈信息
客户端:
public class ClientDemo{
public static void main(String[] args) throws IOException {
//创建客户端Socket对象
Socket s = new Socket("192.168.1.124",10089);
//获取输出流对象,写出数据
OutputStream os = s.getOutputStream();
os.write("天气不错,适合睡觉!".getBytes());
//获取输入流对象,读入数据并显示
InputStream is = s.getInputStream();
byte[] bys = new byte[1024];
int len = is.read(bys);
String client = new String(bys,0,len);
System.out.println("client: "+client);
//关闭资源
s.close();
}
}
服务器端:
public class ServerDemo{
public static void main(String[] args) throws IOException {
//创建服务器端对象
ServerSocket ss = new ServerSocket(10089);
//监听客户端连接,返回Socket对象
Socket s = ss.accept();
//获取输入流对象,读入数据并显示
InputStream is = s.InputStream();
byte[] bys = new byte[1024];
len = is.read(bys);
String server = new String(bys,0,len);
System.out.println("server: " + server);
//获取输出流对象,写出反馈信息
OutputStream os = s.getOutputStream();
os.write("数据已收到!".getBytes());
//关闭资源
s.close();
}
}