同学网上找的代码,说会乱码。看了源码,没发现什么原因,运行起来对方发送过来的字符串确实是乱码的。同学用的NetBeans我用的Eclipse,而NetBeans默认的编码是UTF-8,Eclipse默认的是GBK;琢磨着就是这个引起的。。。。都改成一样的编码就没事了。代码如下:
- package test;
- import java.awt.BorderLayout;
- import java.awt.List;
- import java.awt.TextField;
- import java.awt.event.ActionEvent;
- import java.awt.event.ActionListener;
- import java.io.IOException;
- import java.net.DatagramPacket;
- import java.net.DatagramSocket;
- import java.net.InetAddress;
- import java.net.SocketException;
- import java.net.UnknownHostException;
- import javax.swing.JFrame;
- import javax.swing.JPanel;
- public class netchat {
- JFrame jf = new JFrame("聊天窗口");
- List l = new List(6);
- JPanel jp = new JPanel();
- TextField tip = new TextField(15);
- TextField tdata = new TextField(15);
- DatagramSocket ds;
- // DatagramPacket dp;
- public netchat() {
- tip.setText("127.0.0.1");
- try {
- ds = new DatagramSocket(3000);
- } catch (SocketException e) {
- e.printStackTrace();
- }
- new Thread(new Runnable()
- {
- DatagramPacket dp;
- public void run() {
- byte[] buf = new byte[1024];
- dp = new DatagramPacket(buf, 1024);
- while (true) {
- try {
- ds.receive(dp);
- // l.add(dp.getAddress().getHostName()+"say:"+new
- // String(buf,0,dp.getLength()), -1);
- // l.add(dp.getAddress().getHostAddress()+" say:"+new
- // String(buf,0,+dp.getLength()), -1);
- System.out.println("aaaa");
- String str = new String(dp.getData(), 0, dp.getLength());
- System.out.println("数据1是:" + str);
- String str2 = new String(buf, 0, dp.getLength());
- System.out.println("数据2是:" + str2);
- l.add(dp.getAddress().getHostAddress() + " say:" + str,
- -1);
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- }).start();
- }
- public static void main(String[] args) {
- new netchat().init();
- }
- private void init() {
- jf.add(l);
- jp.add(tip, BorderLayout.WEST);
- jp.add(tdata, BorderLayout.EAST);
- jf.add(jp, BorderLayout.SOUTH);
- jf.setSize(400, 300);
- jf.setVisible(true);
- jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- tdata.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent e) {
- byte[] buf;
- String str222 = e.getActionCommand();
- buf = str222.getBytes();
- System.out.println("ddd=" + str222);
- l.add("我说:" + str222, -1);
- // buf = e.getActionCommand().getBytes();
- DatagramPacket dp;
- try {
- dp = new DatagramPacket(buf, buf.length, InetAddress
- .getByName(tip.getText()), 3000);
- ds.send(dp);
- } catch (UnknownHostException e1) {
- e1.printStackTrace();
- } catch (IOException e1) {
- e1.printStackTrace();
- }
- ((TextField) e.getSource()).setText("");
- }
- });
- }
- }
运行结果就是一个小窗体。。。