2017년 8월 30일 수요일

이클립스 설치후 환경 설정(한글설정)





web.xml에 ㅊ가 하기.

</servlet-mapping>


<filter>
 <filter-name>encodingFilter</filter-name>
 <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
 <init-param>
  <param-name>encoding</param-name>
  <param-value>UTF-8</param-value>
 </init-param>
</filter>
<filter-mapping>
 <filter-name>encodingFilter</filter-name>
 <url-pattern>/*</url-pattern>
</filter-mapping>

</web-app



jsp파일의 가장 위쪽에 추가
<%@ page language="java" contentType="text/html; charset=UTF-8"
   pageEncoding="UTF-8"%

preference에서 web과 workspace 카테고리에서 utf-8 설정바꿔주는것도 잊지 않기



DB 포트번호 변경하기, 디벨로퍼 설치

<run SQL cmd >

conn /as sysdba //커넥트(설치 한 후 확인)
SELECT DBMS_XDB.GETHTTPPORT() FROM DUAL;
//(포트번호 확인 명령어) 
EXEC DBMS_XDB.SETHTTPPORT(9090);
//(포트번호 변경 명령어)

SELECT DBMS_XDB.GETHTTPPORT() FROM DUAL;
//(다시한번더 포트번호 확인






sql developer 실행시 (최초1회) (자바 경로설정)







2017년 8월 10일 목요일

mqtt이용 채팅 웹 구현


먼저 라이브러리를 넣자;
javascripts 폴더안에 jquery랑 mqtt 라이브러리 넣어주자

mqtt다운 받는 링크



project1/view/ mqtt1.ejs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55

<!DOCTYPE html>
<html>
<head>
<title>mqtt</title>
 <script src="/javascripts/jquery.js" type="text/javascript"></script>
 <script src="/javascripts/mqttws31.min.js" type="text/javascript"></script>
<script type="text/javascript">
    var client = new Paho.MQTT.Client('211.110.165.201',1884,'jdh1');
    client.connect({onSuccess:Conn});//연결성공
    client.onMessageArrived = MsgArriv ; //메세지
    client.onConnectionLost = onConLost; //연결종료
    function Conn(){ //연결되었을때
      client.subscribe('<%= topic %>'+'/#');
      //client.subscribe('class603/#'); //구독자 등록      
    };
    function MsgArriv(message){
      console.log(message);
      recvMsg(message);
    };
    //연결이 끝어지면
    function onConLost(responseObject){
      alert('disconnect'); //서버가 끊기면
    };
    function sendMessage(t, m){
      message = new Paho.MQTT.Message(m);
      message.destinationName = t;
      client.send(message);
    }
    $(document).ready(function(){
      recvMsg = function(msg){
        $('#div_out').html(msg.payloadString);
      };
      $('#txt_msg').keyup(function(event){
        if(event.which == 13){
          var m = $('#txt_msg').val();
          sendMessage('<%= topic %>'+'/jdh', m);
          //sendMessage('class603/jdh', m);
        }
      });
  });
 </script>
</head>
<body>
  <input type="text"  id="txt_msg"  />
  <div id="div_out"></div>
 </body>
</html>
cs


room.ejs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<!DOCTYPE html>
<html>
  <head>
    <title></title>
    <link rel='stylesheet' href='/stylesheets/style.css' />
  </head>
  <body>
    <h1></h1>
    
    <table width="200px" border="1px">
      <tr>
        <th>방이름</th>
        <th>비고</th>
      </tr><br>
      <for(var i=0; i<list.length; i++){ %>
        <tr>
          <td><%= list[i].topic %></td>
          <td><a href = "mqtt1?t=<%= list[i].topic %>">참여</a></td>
        </tr>
      <% } %>
    </table>
  </body>
</html>
cs


member.js


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
router.get('/room'function(req, res, next) {
   var sql = "SELECT * FROM chat_room";
  dbconn.query(sql,function(err,rows,fileds){
    if(!err){
      if(rows.length > 0){
        //room.ejs로 list정보 전달
        res.render('room',{'list':rows});
      }
    }
  });  
});
router.get('/mqtt1'function(req, res, next) {
  var t = req.query.t; //req.body.(name값)
  
res.render('mqtt1',{topic:t});
});
cs


실행화면





2017년 8월 9일 수요일

JAVA로 보낸 메세지, 실시간으로 웹으로 받기 ( mqtt 사용)


pom에서 새로운 라이브러리 추가

 <위치>


<코드>

1
2
3
4
5
6
7
8
9
10
11
12
    <repositories>
       <repository>
         <id>Eclipse Paho Repo</id>
         <url>https://repo.eclipse.org/content/repositories/paho-releases/</url>
       </repository>
     </repositories>
  
    <dependency>
     <groupId>org.eclipse.paho</groupId>
     <artifactId>org.eclipse.paho.client.mqttv3</artifactId>
     <version>1.0.2</version>
    </dependency>
cs



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
//Exam3.src.com.ds.ex.MpttClass.java
 
package com.ds.ex;
 
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
 
public class MqttClass implements MqttCallback{
    private MqttClient client = null;
    
    public MqttClass(){ //서버에 접속
        new Thread(task1).start();
    }
    
    private MyEventListner listener = null;
    private MemoryPersistence persistence = new MemoryPersistence();
    
    Runnable task1 = new Runnable(){
        @Override
        public void run() {
            try {
                //new MqttClient()
                client = new MqttClient("tcp://211.110.165.201:1883""h78786565", persistence);
                MqttConnectOptions connopt = new MqttConnectOptions();
                connopt.setCleanSession(true);
                client.connect(connopt);
                client.setCallback(MqttClass.this);
                client.subscribe("class603/#"0);
        
                new MyFrame(MqttClass.this);
            } catch (MqttException e) {
                System.out.println("ERR0"+e.getStackTrace());
            }
        }
    };
 
    public void sendMessage(String payload){
        MqttMessage message = new MqttMessage();
        message.setPayload(payload.getBytes()); //String -> byte[]
        //message.setQos(0);
        try {
            if(client.isConnected()){
                client.publish("class603/hss1", message);
            }
        } catch (MqttException e) {
            System.out.println("ERR1-"+e.getStackTrace());//+e.getMessage());
        }
    }
 
    @Override
    public void connectionLost(Throwable arg0) {
        try {
            System.out.println("disconect");
            client.close();
        } catch (MqttException e) {
            System.out.println("ERR"+e.getMessage());
        }
    }
 
    @Override
    public void deliveryComplete(IMqttDeliveryToken arg0) {
        
    }
 
    public void setMyEventListner(MyEventListner listener){
        this.listener = listener;
    }
    
    @Override
    public void messageArrived(String arg0, MqttMessage arg1) throws Exception {
        System.out.println(arg0+","+arg1);
        listener.recvMsg(arg0, arg1);
    }
}
 
 
 
cs



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
//Exam3.src.com.ds.ex.MyFrame.java
package com.ds.ex;
 
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
 
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
 
import org.eclipse.paho.client.mqttv3.MqttMessage;
 
public class MyFrame extends JFrame implements ActionListener,MyEventListner{
    
    private static final long serialVersionUID = 1L;
 
    @Override
    public void recvMsg(String arg0, MqttMessage arg1) {
        System.out.println(arg0+","+arg1);
        String tmp = out.getText();
        out.setText(arg0+","+arg1+"\n"+tmp);
    }
        
    private JTextField msg = new JTextField(30);
    private JButton btn = new JButton("보내기");    
    private JTextArea out = new JTextArea(20,40);
    private JPanel panel = new JPanel();
    private MqttClass mqtt = null;
    
    public MyFrame(MqttClass mqtt){
        this();
        this.mqtt = mqtt;
        this.mqtt.setMyEventListner(this);
    }
    
    public MyFrame(){
        super("타이틀");
        setSize(500,600);
        panel.setLayout(new FlowLayout()); //<div
        panel.add(msg); //input type 
        panel.add(btn); //button
        panel.add(out); //textarea
        add(panel); //jframe에 div
        
        btn.addActionListener(this); //통지할 수 있게 설정
        
        setVisible(true);
        
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
 
    @Override
    public void actionPerformed(ActionEvent arg0) {
        JButton b = (JButton) arg0.getSource();
        if(b.getText().equals("보내기")){
            //System.out.println("버튼 클릭됨");
            mqtt.sendMessage(msg.getText());
        }
    }
}
 
 
 
cs

인터페이스.

1
2
3
4
5
6
7
8
9
//Exam3.src.com.ds.ex.MyEventListner.java
package com.ds.ex;
 
import org.eclipse.paho.client.mqttv3.MqttMessage;
 
public interface MyEventListner {
    public void recvMsg(String arg0, MqttMessage arg1);
}
 
cs

메인
1
2
3
4
5
6
7
package com.ds.ex;
 
public class Main {
    public static void main(String[] args) {
        new MqttClass();
    }
}
cs


<실행화면>




--------------------------------연동하기 -------------------------------------------------

VisualCode 로 작성

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//project1.member.js
 
// mqtt ------------------------------
var mqtt=require('mqtt');
var mqttclient = mqtt.connect("tcp://211.110.165.201:1883?clientid=jdh");
mqttclient.on('connect',function(){
  mqttclient.subscribe('class603/#');
  mqttclient.publish('class603/''hello Daeho');
});
 
mqttclient.on('message',function(topic, message){
  console.log(topic.toString()+","+message.toString())
 // mqttclient.end();
});
 
//=============================== Controller=========================
router.get('/mqtt', function(req, res, next) {
res.render('mqtt',{});
});
 
cs



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
//project1.views.mqtt.ejs
 
<!DOCTYPE html>
<html>
<head>
<title>mqtt</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.0.1/mqttws31.min.js" type="text/javascript"></script>
<script>
 var client = new Paho.MQTT.Client('211.110.165.201'1884'hss34');
  client.onConnectionLost = onConnectionLost;
 client.onMessageArrived = onMessageArrived;
 client.connect({onSuccess:onConnect});
  function onConnect() {
   // Once a connection has been made, make a subscription and send a message.
   console.log("onConnect");
   client.subscribe("class603/#");
   message = new Paho.MQTT.Message("Hello");
   message.destinationName = "class603/hss34";
   client.send(message);
 };
  function onConnectionLost(responseObject) {
   if (responseObject.errorCode !== 0)
   console.log("onConnectionLost:"+responseObject.errorMessage);
 };
  function onMessageArrived(message) {
   console.log(message);
   var txt_out = document.getElementById("txt_out");
   txt_out.value = message.destinationName+" - "+ message.payloadString +"\n"+ txt_out.value;
   console.log("onMessageArrived:"+message.payloadString);
   //client.disconnect();
 }; 
 
 function sendMessage(){
   var msg = document.getElementById("txt_msg");
   message = new Paho.MQTT.Message(msg.value);
   message.destinationName = "class603/hss4";
   client.send(message);
 };
 
 </script>
</head>
<body>
   <input type="text"  id="txt_msg" />
   <input type="button"  id="btn_msg" value="보내기" onclick="sendMessage();"/>
   <textarea rows="10" style="width:100%" id="txt_out"></textarea>
 
 </body>
</html>
 
 
cs

<실행화면>



-----------------------------------새로운 아이디어로 실행(조금 변경함)----------------------


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
//project1.views.mqtt.ejs
 
<!DOCTYPE html>
<html>
<head>
<title>mqtt</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.0.1/mqttws31.min.js" type="text/javascript"></script>
<script>
 var client = new Paho.MQTT.Client('211.110.165.201'1884'jdh');
  client.onConnectionLost = onConnectionLost;
 client.onMessageArrived = onMessageArrived;
 client.connect({onSuccess:onConnect});
  function onConnect() {
   // Once a connection has been made, make a subscription and send a message.
   console.log("onConnect");
   client.subscribe("class603/#");
   /*
   message = new Paho.MQTT.Message("Hello");
   message.destinationName = "class603/jdh";
   client.send(message);*/
 };
  function onConnectionLost(responseObject) {
   if (responseObject.errorCode !== 0)
   console.log("onConnectionLost:"+responseObject.errorMessage);
 };
  function onMessageArrived(message) {
   console.log(message);
   /*var txt_out = document.getElementById("txt_out");
   txt_out.value = message.destinationName+" - "+ message.payloadString +"\n"+ txt_out.value;
   console.log("onMessageArrived:"+message.payloadString);
   */
   var div = document.getElementById("div_out");
   div.innerHTML = message.payloadString;
   //client.disconnect();
 }; 
 
 function sendMessage(){
   var msg = document.getElementById("txt_msg");
   message = new Paho.MQTT.Message(msg.value);
   message.destinationName = "class603/jdh";
   client.send(message);
 };
 
 </script>
</head>
<body>
   <!--<input type="text"  id="txt_msg"  />
   <input type="button"  id="btn_msg" value="보내기" onclick="sendMessage();"/>
   <textarea rows="10" style="width:100%" id="txt_out"></textarea>-->
   <div id="div_out"></div>
 </body>
</html>
 
 
cs

<실행화면>

네이버 소스코드를 복사해서 자바에 보내면
다음과 같이 내 페이지로 화면이 출력되는 것이 보인다.