netty 网络通信

由于小时候的一款游戏已经停服,里边全是儿时的回忆,自己想在业余时间做一个游戏。就算失败了也算是扩展自己的能力吧。以下是使用窗体的测试,但主要想使用的是unity做客户端。unity 本人也不会在一点点摸索。希望感兴趣的大哥大姐们教教在下。

先看效果

在这里插入图片描述
使用工具
通信 netty
后台 springboot mybatis mysql
简单实现

服务端代码地址
https://gitee.com/shi-xingze/xlserver.git

客户端测试窗体

客户端测试maven

 <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.73</version>
        </dependency>
        <dependency>
            <groupId>io.netty</groupId>
            <artifactId>netty-codec-haproxy</artifactId>
        </dependency>

1、登录窗体


package com.example.xianglongcliet.jframe;

import com.alibaba.fastjson.JSONObject;
import io.netty.channel.ChannelHandlerContext;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

public class SwingJframe extends JFrame {

    private static void Login(JButton button, String username, String password, JLabel leabl){
        button.addActionListener(new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                leabl.setText(username);
            }
        });
    }

    public static void main(String[] args) throws Exception {
        JFrame f1 = new JFrame();
        f1.setTitle("欢迎登陆");
        f1.setBounds(400, 200, 400, 270);
        f1.setResizable(false);
        // 实例化各组件
        Container con = f1.getContentPane(); //生成一个容器
        con.setLayout(new GridLayout(7,1));  //设置容器布局
        JLabel welcome = new JLabel("欢迎登陆本系统");
        JLabel usname = new JLabel();
        JLabel paswd = new JLabel();
        JTextField text1 = new JTextField(12);
        JPasswordField text2 = new JPasswordField(12);
        JButton login = new JButton("登陆");
        JButton regist = new JButton("注册");
        JPanel p1 = new JPanel();
        JPanel p2 = new JPanel();
        JPanel p3 = new JPanel();
        JPanel p4 = new JPanel();
        welcome.setFont(new Font("宋体", Font.BOLD, 20));
        p1.add(welcome);
        con.add(p1);
        usname.setText("账号:");
        paswd.setText("密码:");
        p2.add(usname);
        p2.add(text1);
        con.add(p2);
        p3.add(paswd);
        p3.add(text2);
        con.add(p3);
        p4.add(login);
         p4.add(regist);
        con.add(p4);
       Socket socket = new Socket("127.0.0.1",8979,true);
        System.out.println("连接服务器成功");

       socket.getChannel();
        login.addActionListener(new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    System.out.println(socket+"111");
                    System.out.println(socket.getPort());
                    try {
                        ScokectMessger messger = new ScokectMessger();
                        messger.setModetype(1);
                        messger.setModeCode(1002);
                        messger.setDataLength(4L);

                        Map<String, Object> map = new HashMap<>();
                        map.put("username", text1.getText());
                        map.put("password", text2.getText());
                        messger.setData(JSONObject.toJSONString(map));
                        String oo = JSONObject.toJSONString(messger);
                        send(oo, socket);
                        String ss = receive(socket);
                        AjaxResult data = JSONObject.parseObject(ss, AjaxResult.class);
                        if (data.getCode() == 200) {
                            //发送角色信息
                            Play play = new Play();
                            play.setPlayName("张三");
                            play.setMapCode(1);
                            play.setX(1);
                            play.setY(1);
                            messger.setData(JSONObject.toJSONString(play));
                            messger.setModeCode(2001);
                            messger.setModetype(2);
                            send(JSONObject.toJSONString(messger), socket);
                            String ss2 = receive(socket);
                            createScanens(ss2,socket);
                            welcome.setText(ss2);

                        } else {
                            welcome.setText(ss);
                        }

                    } finally {

                    }
                        } catch (IOException ex) {
                    throw new RuntimeException(ex);
                } catch (Exception ex) {
                    throw new RuntimeException(ex);
                }

            }
        });
        f1.setVisible(true);

    }
    /**
     * 发送消息
     * @param msg
     * @throws Exception
     */
    public static void send(String msg, Socket socket) throws Exception {

//            writer.flush();// 写完后要记得flush
        System.out.println("Cliect[port:" +socket.getLocalAddress()+ socket.getLocalPort() + "] 消息发送成功");
        PrintWriter printWriter = new PrintWriter(socket.getOutputStream());
        printWriter.write(msg);
        printWriter.flush();
    }


    /**
     * 接收消息
     * @throws Exception
     */
    public static String receive(Socket socket) throws IOException {
        InputStream inputStream = socket.getInputStream();
        byte[] bytes = new byte[2048];
        int len;
        StringBuilder sb = new StringBuilder();
        len = inputStream.read(bytes);
        sb.append(new String(bytes, 0, len,"UTF-8"));



        System.out.println("收到响应报文: " + sb);
        return sb.toString();
    }

    /**
     * 创建场景并初始化
     */
    public static void  createScanens(String allPlay,Socket socket){
      //  Map<String,Play> Json
        Map<String,JSONObject> data = JSONObject.parseObject(allPlay, Map.class);
        System.out.println("转对象"+data);
        SacenJframe.getScaen(data,socket);
    }
}

1、移动界面窗体

 package com.example.xianglongcliet.jframe;

import com.alibaba.fastjson.JSONObject;
import org.springframework.util.StringUtils;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

public class SacenJframe extends JFrame {

  public static     SacenJframe sacenJframe = new SacenJframe();

  public Map componentMap;
    public static void init(){
        sacenJframe.setTitle("欢迎登陆");
        sacenJframe.setBounds(400, 200, 800, 400);
        sacenJframe.setResizable(false);
        sacenJframe.setLayout(null);
        // 实例化各组件
    }
    private void createComponentMap() {

        componentMap = new HashMap();

        Component[] components = sacenJframe.getContentPane().getComponents();

        for (int i=0; i < components.length; i++) {

            componentMap.put(components[i].getName(), components[i]);

        }

    }

    public Component getComponentByName(String name) {

        if (componentMap.containsKey(name)) {

            return (Component) componentMap.get(name);

        }

        else return null;

    }

    public static void CreateThred(Socket socket){
        System.out.println("开启接收线程通道");
        new Thread(() -> {
            System.out.println("进入线程");
            while (true){
                try {

                    String ss =  receive(socket);
                    if (!StringUtils.isEmpty(ss)){
                        System.out.println("线程接收报文["+ss+"]");
                    }

                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        });
    }
   public static  void getScaen(Map<String,JSONObject> plays, Socket socket){
       MessageThread thread = new MessageThread(socket,sacenJframe);
       thread.start();
       init();
       //  Map<String,Play> Json

       Map<String, JButton> labelMap = new HashMap<>();
       for (Map.Entry<String, JSONObject> entry : plays.entrySet()) {

       JButton label = new JButton((String) entry.getValue().get("playName"));
       try {
           label.setBounds(Integer.parseInt((String)entry.getValue().get("X")),Integer.parseInt((String) entry.getValue().get("Y")),50,50);
           label.setName((String) entry.getValue().get("playName"));
       }catch (Exception e){
           System.out.println(e);
       }

        labelMap.put((String) entry.getValue().get("playName"),label);
       }
       for (Map.Entry<String, JButton> entry : labelMap.entrySet()) {
          Rectangle j =  entry.getValue().getBounds();
          entry.getValue().setBounds(j.x+20, j.y+20, 70,50);
           entry.getValue().setName(entry.getKey());
           SacenJframe.sacenJframe.add( entry.getValue());
       }


       JButton up = new JButton("向上");
       up.setBounds(200,250,70,30);
       up.setName("向上");
       JButton xia = new JButton("向下");
       xia.setBounds(200,310,70,30);
       xia.setName("向下");
       JButton zuo = new JButton("向左");
       zuo.setBounds(100,270,70,30);
       zuo.setName("向左");
       JButton you = new JButton("向右");
       you.setBounds(300,270,70,30);
       you.setName("向右");
       sacenJframe.add(up);
       sacenJframe.add(xia);
       sacenJframe.add(zuo);
       sacenJframe.add(you);

       xia.addActionListener(new AbstractAction() {
           @Override
           public void actionPerformed(ActionEvent e) {
               System.out.println("项下");
              String ip = socket.getLocalAddress().toString().split("/")[1];
               String key = ip+":"+socket.getLocalPort();
               JSONObject jsonObject = plays.get(key);
               int x = (int)jsonObject.get("x");
               x+=10;
               jsonObject.put("x",x);

               ScokectMessger messger = new ScokectMessger();
               messger.setData(JSONObject.toJSONString(jsonObject));
               messger.setModeCode(2002);
               messger.setModetype(2);
               try {
                   send(JSONObject.toJSONString(messger), socket);
               } catch (Exception ex) {
                   throw new RuntimeException(ex);
               }
//               try {
//                   String ss2 = receive(socket);
//
//               } catch (IOException ex) {
//                   throw new RuntimeException(ex);
//               }
           }
       });
       SacenJframe.sacenJframe.setVisible(true);
   }


    /**
     * 发送消息
     * @param msg
     * @throws Exception
     */
    public static void send(String msg, Socket socket) throws Exception {

//            writer.flush();// 写完后要记得flush
        System.out.println("Cliect[port:" +socket.getLocalAddress()+ socket.getLocalPort() + "] 消息发送成功");
        PrintWriter printWriter = new PrintWriter(socket.getOutputStream());
        printWriter.write(msg);
        printWriter.flush();
    }

    /**
     * 接收消息
     * @throws Exception
     */
    public static String receive(Socket socket) throws IOException {
        InputStream inputStream = socket.getInputStream();
        byte[] bytes = new byte[2048];
        int len;
        StringBuilder sb = new StringBuilder();
        len = inputStream.read(bytes);
        sb.append(new String(bytes, 0, len,"UTF-8"));
        System.out.println("地址专用通道: " + sb);
        return sb.toString();
    }
}

3、数据接收线程类

package com.example.xianglongcliet.jframe;

import com.alibaba.fastjson.JSONObject;

import org.springframework.util.StringUtils;

import java.awt.*;
import java.io.IOException;
import java.net.Socket;

public class MessageThread extends Thread{

    public Socket socket =null;

    public  SacenJframe sacenJframe = null;
    public  MessageThread(Socket socket,SacenJframe sacenJframe){
        this.socket = socket;
        this.sacenJframe = sacenJframe;
    }

    @Override
    public void run() {
        System.out.println("进入线程");
        while (true){
            try {

                String ss =  SacenJframe.receive(socket);
                if (!StringUtils.isEmpty(ss)){
                    Play play =  JSONObject.parseObject(ss, Play.class);
                    System.out.println("线程接收报文["+ss+"]");

                    Component[] components = sacenJframe.getContentPane().getComponents();

                    for (int i=0; i < components.length; i++) {
                        try {
                            System.out.println(  components[i].getName());
                            System.out.println(components[i].getFont());
                            if (components[i].getName().equals(play.getPlayName())){

                                System.out.println("进来了");
                                components[i].setBounds(play.getX(),play.getY(),70,50);
                            }
                        }catch (Exception e){
                            System.out.println(e);
                        }


                    }

                }

            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值