JAVA网络编程——简单的聊天程序

简单的交互,可以互相发送信息。

 

NetSendDemo.java

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.*;
public class NetSendDemo {


 public static void main(String[] args) {
  Thread t1 = new NetReceive();
  t1.start();
  try {
   DatagramSocket ds = new DatagramSocket();
   byte[] buf = null;
   InetAddress is = InetAddress.getByName("127.0.0.1");
   
   BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
   while((buf=br.readLine().getBytes())!=null){
    
   DatagramPacket dp = new DatagramPacket(buf,buf.length,is,9000);
   ds.send(dp);
   }
   ds.close();
  } catch (SocketException e) {
   e.printStackTrace();
  } catch (Exception e){
   
  }
  
}}

class NetReceive extends Thread{
 
 public void run(){
  
  DatagramSocket ds;
  try {
   ds = new DatagramSocket(9001);
   while(true){
    byte[] buf = new byte[1024];
    DatagramPacket dp = new DatagramPacket(buf,buf.length);
    ds.receive(dp);
    String ip = dp.getAddress().getHostAddress();
    String data = new String(dp.getData(),0,dp.getLength());
    int port = dp.getPort();
    System.out.println(ip+":"+data+":"+port);}
  } catch (Exception e) {
   e.printStackTrace();
  }
 }
}

 

NetReceiveDemo.java

 

import java.net.*;
import java.io.*;
public class NetReceiveDemo {
 public static void main(String[] args) throws Exception {
  DatagramSocket ds = new DatagramSocket(9000);
  Thread t2 = new NetSend();
  t2.start();
  while(true){
  byte[] buf = new byte[1024];
  DatagramPacket dp = new DatagramPacket(buf,buf.length);
  ds.receive(dp);
  String ip = dp.getAddress().getHostAddress();
  String data = new String(dp.getData(),0,dp.getLength());
  int port = dp.getPort();
  System.out.println(ip+":"+data+":"+port);
  }
  
  
 }

}
class NetSend extends Thread{
 public void run(){
 try {
  DatagramSocket ds = new DatagramSocket();
  byte[] buf = null;
  InetAddress is = InetAddress.getByName("127.0.0.1");
  
  BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  while((buf=br.readLine().getBytes())!=null){
   
  DatagramPacket dp = new DatagramPacket(buf,buf.length,is,9009);
  ds.send(dp);
  }
  ds.close();
 } catch (SocketException e) {
  e.printStackTrace();
 } catch (Exception e){
  
 }
}
 
}


 

你可能感兴趣的:(JAVA网络编程——简单的聊天程序)