Merhaba değerli Java dostları, bir önceki yazımda WebSocket server konusuna değinmiştim. Şimdi de client tarafına bakacağız. Emin olun ki en az server kadar kolay olacak 🙂 .

Önce maven ayarlarımız.

 

  <dependency>
<groupId>javax.websocket</groupId>
<artifactId>javax.websocket-api</artifactId>
<version>1.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.glassfish.tyrus.bundles</groupId>
<artifactId>tyrus-standalone-client</artifactId>
<version>1.9</version>
</dependency>

 

Şimdi de örnek sınıfmız.

 

import java.io.IOException;
import java.io.Serializable;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;import javax.websocket.ClientEndpoint;
import javax.websocket.CloseReason;
import javax.websocket.ContainerProvider;
import javax.websocket.DeploymentException;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.WebSocketContainer;
@ClientEndpoint
public class WebSocketClient implements Serializable {private static final long serialVersionUID = 1L;
private Session session = null;

@OnOpen
public void onOpen(Session session) {
setSession(session);
}

@OnClose
public void onClose(Session session, CloseReason closeReason) {
setSession(null);
}

@OnMessage
public void onMessage(String message) {
}

public void connect(String serverURI) throws WebSocketException {
if (isSessionValid())
disconnect();
WebSocketContainer container = ContainerProvider.getWebSocketContainer();
try {
container.connectToServer(this, new URI(serverURI));
} catch (DeploymentException | IOException | URISyntaxException e) {
throw new WebSocketException(“An exception occured during connecting to web socket server.”, e);
}
}

public void disconnect() throws WebSocketException {
if (isSessionValid())
try {
getSession().close();
} catch (IOException e) {
throw new WebSocketException(“An exception occured during closing connection.”, e);
}
}

public boolean isSessionValid() {
return getSession() != null && getSession().isOpen();
}

public Session getSession() {
return session;
}

private void setSession(Session session) {
this.session = session;
}

}

 

@ClientEndpoint ile bu sınıfın bir client olduğunu belirttik. @OnOpen ile servera bağlandığımız düşeceğimiz metod tanımlamış oluyoruz. @OnClose ile de tam tersi bağlantıyı kopardığımızda düşüyoruz. @OnMessage ile server bir mesaj yayınladığında bunu yakalamış oluyoruz. Bunun dışında tanımladığımız connect ve disconnect metotları ile de server ile olan bağlantımızı yönetiyoruz. İşte bu kadar basit.

Bol Java’ lı günler dileğiyle… 😀

Categories:

No responses yet

Bir yanıt yazın

E-posta adresiniz yayınlanmayacak. Gerekli alanlar * ile işaretlenmişlerdir