Past articles: https://qiita.com/take4eng/items/d0b009c48ee8c3fe420a
As described in the previous article above, create a server program in Java and perform socket communication. ⇒Since HTTP communication is analyzed by pushing it, the code is uselessly complicated.
There are many APIs related to socket communication in Java EE, and it is very easy to implement. Many people have already summarized it, but I will summarize the implementation contents.
Even though a convenient API is prepared, no one does analysis by pushing it. Even if I google it, it doesn't come out easily ...
Describes the basic WebSocket API. There are many APIs other than those introduced here, but you can google if necessary.
import javax.websocket.server.ServerEndpoint;
@ServerEndpoint("/Context path")
public class SanpleEndpoint {
}
/*
Import each class
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
*/
//Processing when connecting to a client
@OnOpen
public void onOpen(Session session) {
}
//What to do when a message is received from a client
@OnMessage
public void onMessage(String message) {
}
//What to do when an error occurs
@OnError
public void onError(Throwable error) {
}
//What to do when the connection with the client is lost
@OnClose
public void onClose(Session session) {
}
Server program
import java.io.IOException;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
//Annotation that indicates that it is a server-side class of WebSocket.
//argument(wSck)Represents the URI used when connecting from the client.
@ServerEndpoint(value = "/wSck")
public class SocketFree2 {
//Create a client session thread(Save each session for each client)
//Set: Collection with no duplicate elements
//CopyOnWriteArrayList:java.util.A thread-safe version of Set
private static Set<Session> user = new CopyOnWriteArraySet<>();
@OnOpen//When connecting with a client
public void onOpen(Session mySession) {
System.out.println("connect ID:"+mySession.getId());//session.getId():Get session ID
user.add(mySession);//Add session for each client to list
}
@OnMessage//When data is sent from the client
public void onMessage(String text , Session mySession) {//The arguments are the text sent and the session from which it originated.
System.out.println(text);
//getAsyncRemote(): Get an instance of RemoteEndpoint
//sendText(String): Send text to client
for (Session user : user) {
user.getAsyncRemote().sendText(text);
System.out.println(user.getId()+"Second"+mySession.getId()+"I sent the second message!");
}
if(text.equals("bye")) onClose(mySession);//Disconnect if text is "bye"
}
@OnClose//When the client disconnects
public void onClose(Session mySession) {
System.out.println("disconnect ID:"+mySession.getId());
user.remove(mySession);//Remove disconnected client session from list
try {
mySession.close();//Disconnect with close method
} catch (IOException e) {
System.err.println("An error has occurred: " + e);
}
}
}
@ServerEndpoint(value = "/wSck")
Create a list that identifies each client
private static Set<Session> user = new CopyOnWriteArraySet<>();
user.add(mySession);
Four. onMessage method: Send the received text to the client as it is
⇒ Send to all clients connected by for statement
user.getAsyncRemote().sendText(text);
Five. onClose method: delete the disconnected client
5-1. Remove from user list: ʻuser.remove (mySession); 5-2. Delete session and disconnect:
mySession.close ();`
Change the address of the client program and execute it with a web browser.
var wSck = new WebSocket ("ws: // localhost: 8080 / project name / context path ");
(This time " ws: // localhost: 8080 / freeWeb2 / wSck "
)A chat application that displays the sent contents is completed. It also supports access from multiple browsers.
Socket communication was very easy to do by using the API. Compared to the one described in the past article, the amount of code written is about 1/4. It's amazing. Super easy.
Besides, it seems that encoding, decoding processing and handling of json data can be done easily. I haven't used it this time, but it will be necessary for full-scale development. See the reference page for details.
Recommended Posts