- import java.io.BufferedInputStream;
- import java.io.BufferedReader;
- import java.io.InputStreamReader;
- import java.net.DatagramPacket;
- import java.net.DatagramSocket;
- import java.net.InetAddress;
- import java.text.SimpleDateFormat;
- import java.util.Date;
- import java.util.concurrent.Executors;
- public class Demo
- {
- public static void main(String[] args)
- {
- Executors.newSingleThreadExecutor().execute(new Sender());
- Executors.newSingleThreadExecutor().execute(new Receiver());
-
- }
- }
- //此类用于向某个 ip 的某个端口发送信息
- class Sender implements Runnable{
- int port = 2323;//目标端口
- String address="127.0.0.1";//目标 IP
-
- BufferedReader br;
- public void run() {
-
- br = new BufferedReader(new InputStreamReader(System.in));
- String str;
- DatagramSocket socket;
- DatagramPacket packet;
- try {
- socket = new DatagramSocket();
- for (;;) {// 不断输入数据 并发送
- System.out.print("请输入:");
- str = br.readLine();
- byte[] buf = (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " ---->" + str).getBytes();
- packet = new DatagramPacket(buf, buf.length,InetAddress.getByName(address),port);
- socket.send(packet);
- str="";
- }
- } catch (Exception e) {
- System.out.println("发送失败");
- }
- }
- }
- //此类用于 在 固定端口监听 接受信息
- class Receiver implements Runnable{
- int port = 2323;
- public void run() {
-
- try{
- DatagramSocket socket =new DatagramSocket(port);//该端口应与 sender 发送的端口一致
-
- for(;;){
- byte[] buf=new byte[1024];
- DatagramPacket packet =new DatagramPacket(buf, buf.length);
- socket.receive(packet);
- String msg = new String(packet.getData());
- System.out.println(msg);
- }
-
- }catch (Exception e) {
- System.out.println("启动失败");
- }
- }
- }
复制代码 这是我今天在公司时写的一个小程序。在控制台输入信息发送到一个目标IP的某个端口,然后在端口接受信息并显示。现在的问题是 公司的系统用的是日文的,输入的中文在接受端显示的是乱码。我知道是编码问题,可是应该如何解决呢? 试了好多方法不能奏效 请高手指点…… |
|