UDP_program

package comm;
/**
 * @docRoot:UDP程序
 * @author gsp
 * @date:2007-09-18
 * @telephone:80889574
 */
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
public class DataSocket  extends JFrame implements Runnable{
 private static final long serialVersionUID = 1L;
 
 /**程序的显示图标**/
 private ImageIcon icon = new ImageIcon(DataSocket.class.getResource("qq.gif"));
 /**中间的面板**/
 private JPanel pan_center;
 /**聊天记录的滑块**/
 private JScrollPane jsp_scroll_records;
 /**聊天内容**/
 private JTextArea text_chatRecord;
 /**下面的面板**/
 private JPanel pan_bottom;
 /**需要发送的消息**/
 private JTextField text_message;
 /**发送按钮**/
 private JButton btn_send;
 /**接受到的数据**/
 byte[] buf = new byte[256];
 /**建立接受的套间字**/
 private DatagramPacket dp = new DatagramPacket(buf,buf.length);
 
 /**构造方法**/
 public DataSocket()
 {
  try{
   jinint();
  }catch(Exception e)
  {
   JOptionPane.showMessageDialog(this,"应用程序初始化失败");
  }
 }
 /**应用程序初始化**/
 private void jinint()
 {
  /**添加聊天记录**/
  text_chatRecord = new JTextArea(12,35);
  text_chatRecord.setFont(new Font("黑体",1,12));
  text_chatRecord.setEditable(false);
  jsp_scroll_records = new JScrollPane(text_chatRecord);
  pan_center = new JPanel();
  pan_center.add(jsp_scroll_records);
  this.getContentPane().add(pan_center,BorderLayout.CENTER);
  /**添加发送消息的模块**/
  pan_bottom = new JPanel();
  text_message = new JTextField(20);
  text_message.setFont(new Font("黑体",1,12));
  pan_bottom.add(text_message);
  btn_send = new JButton("发送消息");
  pan_bottom.add(btn_send);
  this.getContentPane().add(pan_bottom,BorderLayout.SOUTH);
  /**窗体的外观**/
  this.setTitle("网络聊天程序");
  this.setIconImage(icon.getImage());
  Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
  this.setLocation((screen.width-400)/2,(screen.height-300)/2);
  this.setSize(400,300);
  this.setResizable(false);
  /**添加关闭的监听**/
  this.addWindowListener(new WindowListener(){
   public void windowOpened(WindowEvent arg0) {}
   public void windowClosing(WindowEvent arg0) {}
   public void windowClosed(WindowEvent arg0) {
    dispose();
    System.exit(0);
   }
   public void windowIconified(WindowEvent arg0) {}
   public void windowDeiconified(WindowEvent arg0) {}
   public void windowActivated(WindowEvent arg0) {}
   public void windowDeactivated(WindowEvent arg0) {}
  });
  /**添加btn_send的监听**/
  btn_send.addActionListener(new ActionListener(){
   public void actionPerformed(ActionEvent arg0) {
      sendMessage();
   }
  });  
  this.setVisible(true);
  Thread thread = new Thread(this);
  thread.start();
 }
 /**发送消息**/
 private void sendMessage(){
  try
  {
   if(!text_message.getText().equalsIgnoreCase(""))
   {
          byte[] send_message_str = text_message.getText().getBytes();
          InetAddress address = InetAddress.getByName("localhost");
          DatagramPacket paket = new DatagramPacket(send_message_str,send_message_str.length,address,3000);
          DatagramSocket socket = new DatagramSocket();
          Calendar calendar = Calendar.getInstance();
          String  year = calendar.get(Calendar.YEAR)+"-";
          String month = calendar.get(Calendar.MONTH)<10?"0"+calendar.get(Calendar.MONTH)+"-":calendar.get(Calendar.MONTH)+"-";
          String day = calendar.get(Calendar.DATE) <10?"0"+calendar.get(Calendar.DATE)+"  ":calendar.get(Calendar.DATE)+"  ";
          String hour = calendar.get(Calendar.HOUR_OF_DAY) < 10?"0"+calendar.get(Calendar.HOUR_OF_DAY)+":":calendar.get(Calendar.HOUR_OF_DAY)+":";
          String minute = calendar.get(Calendar.MINUTE)<10?"0"+ calendar.get(Calendar.MINUTE)+":":calendar.get(Calendar.MINUTE)+":";
          String second = calendar.get(Calendar.SECOND)<10?"0"+calendar.get(Calendar.SECOND)+"":calendar.get(Calendar.SECOND)+"  ";
          text_chatRecord.append(year+month+day+hour+minute+second+"DataSocket:/n"+text_message.getText()+"/n");
          socket.send(paket);
   }
  }catch(Exception e)
  {}
 }
 /**test**/
 public static  void  main(String[] args)
 {
  new DataSocket();
 }
 /**线程自动自行的方法**/
 public void run() {
  try
  {
   DatagramSocket socket = new DatagramSocket(3001);
   while(true)
   {
    socket.receive(dp);
    String receive_message = new String(dp.getData());
    Calendar calendar = Calendar.getInstance();
       String  year = calendar.get(Calendar.YEAR)+"-";
       String month = calendar.get(Calendar.MONTH)<10?"0"+calendar.get(Calendar.MONTH)+"-":calendar.get(Calendar.MONTH)+"-";
       String day = calendar.get(Calendar.DATE) <10?"0"+calendar.get(Calendar.DATE)+"  ":calendar.get(Calendar.DATE)+"  ";
       String hour = calendar.get(Calendar.HOUR_OF_DAY) < 10?"0"+calendar.get(Calendar.HOUR_OF_DAY)+":":calendar.get(Calendar.HOUR_OF_DAY)+":";
       String minute = calendar.get(Calendar.MINUTE)<10?"0"+ calendar.get(Calendar.MINUTE)+":":calendar.get(Calendar.MINUTE)+":";
       String second = calendar.get(Calendar.SECOND)<10?"0"+calendar.get(Calendar.SECOND)+"":calendar.get(Calendar.SECOND)+"  ";
       text_chatRecord.append(year+month+day+hour+minute+second+"DataSocket1:/n"+receive_message+"/n");
   }
  }catch(Exception e){}
 }
}  

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
优化并改编以下代码,使其和原来有部分出入但实现效果相同: 1. import socket 2. 3. 4. def receive(): 5. # 创建套接字 6. udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 7. 8. # 准备数据9. file_name = input("Please input the save file name:") 10. 11. # 发送数据 12. ip = input("Please input the sender's ipv4 address:") 13. udp_socket.sendto(file_name.encode('gbk'), (ip, 7788)) 14. 15. # 接收数据 16. recv_data = udp_socket.recvfrom(1024) 17. file_data = recv_data[0] 18. with open(file_name, 'wb') as f: 19. f.write(file_data) 20. print("Receive successfully!") 21. # 关闭套接字 22. udp_socket.close() 23. 24. 25.def send(): 26. # 创建套接字 27. udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 28. 29. # 绑定本地信息 30. localaddr = ('', 7788) 31. udp_socket.bind(localaddr) 32. 33. # 接收数据 34. while True: 35. recv_data = udp_socket.recvfrom(1024) 36. recv_msg = recv_data[0] 37. send_addr = recv_data[1] 38. print("%s:%s" % (str(send_addr), recv_msg.decode('gbk'))) 39. 40. # 读取文件并传输文件 41. with open(recv_msg.decode('gbk'), 'rb') as f: 42. file_data = f.read() 43. udp_socket.sendto(file_data, send_addr) 44. 45. print("Send successfully!") 46. break 47. 48. # 关闭套接字 49. udp_socket.close() 50. 51. 52.if name == 'main': 3553. while True: 54. answer = input("This is a simple program relying on the Udp protocol, \nif you want to send the file," 55. "please input 1,\n if you want to receive th e file, please input 2, \n if you want exit, " 56. "please input 0:\n") 57. if answer == '0': 58. break 59. if answer == '1': 60. send() 61. if answer == '2': 62. receive()
最新发布
05-24

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值