I have ServerHandshakeHandler which extends ChannelInboundHandlerAdapter. Client emulates multiple access to server. After some time of successful communication server stops responding when client tries to connect. It doesn't show any incoming connections. Client restart doesn't help, only restart of server.
I tried to set telnet connection when server stops responding: connection establishes but I can't get any response from server (when server is in normal state, it sends response). Similar situation with nmap -v --packet-trace -sT localhost -p {port} : nmap discovers port as open, but there is no log information about incoming connection on server.
Server:
public class ServerHandshakeHandler extends ChannelInboundHandlerAdapter {
private final ChannelGroup group;
private static final byte HANDSHAKE_SUCCEDED = 1;
private static final byte HANDSHAKE_FAILED = 0;
private static final Logger LOG = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
public ServerHandshakeHandler(ChannelGroup group) {
this.group = group;
}
#Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
LOG.debug("in ServerHandshakeHandler.channelRead");
ByteBuf buf = (ByteBuf) msg;
String someField = getSomeField(buf);
ReferenceCountUtil.release(msg);
if (someField.isEmpty()) {
this.fireHandshakeFailed(ctx);
return;
}
LOG.debug("Removing handshake handler from pipeline.");
ctx.pipeline().remove(this);
this.fireHandshakeSucceeded(ctx);
}
#Override
public void channelActive(final ChannelHandlerContext ctx) {
LOG.debug("in ServerHandshakeHandler.channelActive, group size = " + this.group.size());
this.group.add(ctx.channel());
LOG.debug("Incoming connection from: {}",
ctx.channel().remoteAddress().toString());
}
#Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
LOG.error("exception caught ", cause);
if (ctx.channel().isActive()) {
ctx.channel().close();
} else {
this.fireHandshakeFailed(ctx);
}
}
private void fireHandshakeFailed(ChannelHandlerContext ctx) {
LOG.debug("fire handshake failed");
ByteBuf buf = Unpooled.buffer(1);
buf.writeByte(HANDSHAKE_FAILED);
ctx.channel().writeAndFlush(buf);
ctx.channel().close();
ctx.fireUserEventTriggered(HandshakeEvent.handshakeFailed(ctx.channel()));
}
private void fireHandshakeSucceeded(ChannelHandlerContext ctx) {
LOG.debug("fire handshake succeded");
ByteBuf buf = Unpooled.buffer(1);
buf.writeByte(HANDSHAKE_SUCCEDED);
ctx.channel().writeAndFlush(buf);
ctx.fireUserEventTriggered(HandshakeEvent
.handshakeSucceeded(ctx.channel()));
}
}
Client:
public class MyClient {
private static final Logger LOG = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
private String host;
private int port;
private Socket socket;
public Client(String host, int port) {
this.host = host;
this.port = port;
}
public void send(String id, String message) {
try {
socket = new Socket(host, port);
LOG.debug("connected to server");
if (performHandshake(id)) {
LOG.debug("handshake success");
sendMessage(message);
}
socket.close();;
} catch (IOException ex) {
LOG.error("error while sending data", ex);
}
}
private boolean performHandshake(String id) {
try {
byte[] request = handshakeRequest(id);
writeBytes(request);
byte[] response = readBytes(1);
return (response != null && response.length == 1 && response[0] == 1);
} catch (IOException ex) {
LOG.error("perform handshake error", ex);
return false;
}
}
private byte[] handshakeRequest(String id) throws UnsupportedEncodingException {...}
private void writeBytes(byte[] data) throws IOException {
OutputStream out = socket.getOutputStream();
out.write(data);
}
private byte[] readBytes(int length) throws IOException {
InputStream in = socket.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte buffer[] = new byte[1024];
int currentLength = 0;
while (currentLength < length) {
int size = in.read(buffer); //here client stops waiting server response
if (size == -1) {
throw new IOException("unexpected end of stream");
}
baos.write(buffer, 0, size);
currentLength += size;
}
return baos.toByteArray();
}
}
SOLVED! There was narrow piece of code where I was calling synchronized function with connection to database. This connection cannot be established for some reasons and the function hangs. Thread in this function goes into WAITING state. After a while other treads try to access this function and become BLOCKED. That's why server stops processing incoming connections.
I recommend jvisualvm profiling tool, it helped me to find this bug.
Related
What i'm trying to do is group 2 clients and make them communicate with eachother. So if 2 clients are connected they would only be able to communicate with eachother and if a third client got connected it would not be able to communicate with the 2 other clients but it would create another group of 2 clients and so on... Right now if a client sends a message it send it over to all clients but i'm not sure how to make them communicate in groups of 2 like in a peer-to-peer connection.
class Server {
private static DatagramSocket socket = null;
private static Map<Session, Integer> sessions = new HashMap<Session, Integer>();
private static Session session = new Session();
public static void main(String[] args) {
try {
socket = new DatagramSocket(6066);
} catch (SocketException e) {
System.out.println("[SERVER] Unable to launch server on port: " + socket.getLocalPort());
}
System.out.println("[SERVER] Server launched successfully on port " + socket.getLocalPort());
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
byte[] buffer = new byte[100];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
while (true) {
Arrays.fill(buffer, (byte) 0);
try {
socket.receive(packet);
} catch (IOException e) {
System.out.println("[SERVER] Unable to receive packets from buffer");
}
InetAddress ip = packet.getAddress();
int port = packet.getPort();
String data = new String(packet.getData()).trim();
if(session.getIp1() == null) {
session.setIp1(ip);
session.setPort1(port);
session.setData1(data);
} else {
session.setIp2(ip);
session.setPort2(port);
session.setData2(data);
}
DatagramPacket pt = new DatagramPacket(packet.getData(), packet.getData().length, ip, port);
try {
socket.send(pt);
} catch (IOException e) {
System.out.println("[SERVER] Unable to send packets to client.");
}
}
}
});
thread.start();
}
}
Client:
public class Client {
private static DatagramSocket socket = null;
public static void main(String[] args) {
System.out.println("Send to server:");
Scanner scanner = new Scanner(System.in);
while (true) {
try {
// port shoudn't be the same as in TCP but the port in the datagram packet must
// be the same!
socket = new DatagramSocket();
} catch (SocketException e1) {
System.out.println("[CLIENT] Unable to initiate DatagramSocket");
}
InetAddress ip = null;
try {
ip = InetAddress.getByName("127.0.0.1");
} catch (UnknownHostException e) {
System.out.println("[CLIENT] Unable to determine server IP");
}
// must be in a while loop so we can continuously send messages to server
String message = null;
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
receive();
}
});
thread.start();
while (scanner.hasNextLine()) {
message = scanner.nextLine();
byte[] buffer = message.getBytes();
DatagramPacket packet = new DatagramPacket(buffer, buffer.length, ip, 6066);
try {
socket.send(packet);
} catch (IOException e) {
System.out.println("[CLIENT] Unable to send packet to server");
}
}
}
}
private static void receive() {
// receiving from server
byte[] buffer2 = new byte[100];
DatagramPacket ps = new DatagramPacket(buffer2, buffer2.length);
while (true) {
try {
socket.receive(ps);
} catch (IOException e) {
System.out.println("[CLIENT] Unable to receive packets from server.");
}
System.out.println("[SERVER] " + new String(ps.getData()));
}
}
}
Object class:
public class Session {
private InetAddress ip1;
private int port1;
private String data1;
private InetAddress ip2;
private int port2;
private String data2;
public Session() {
}
public InetAddress getIp1() {
return ip1;
}
public void setIp1(InetAddress ip1) {
this.ip1 = ip1;
}
public int getPort1() {
return port1;
}
public void setPort1(int port1) {
this.port1 = port1;
}
public String getData1() {
return data1;
}
public void setData1(String data1) {
this.data1 = data1;
}
public InetAddress getIp2() {
return ip2;
}
public void setIp2(InetAddress ip2) {
this.ip2 = ip2;
}
public int getPort2() {
return port2;
}
public void setPort2(int port2) {
this.port2 = port2;
}
public String getData2() {
return data2;
}
public void setData2(String data2) {
this.data2 = data2;
}
}
Currently, you store the client's information in an array. Make an object where it will contain two client session's data. When a new client is attempting to connect, see if there are any objects that have a free spot, if not, create a new object and await a new participant; otherwise, join an existing session.
Hackish way: Create a Map<ObjectHere, UserCount> then filter based on userCounts = 1 and then join the session to the first returned Object.
I have a problem with communication between client and server using UDP protocol in Java. I made Client and Server classes and two classes SingleCom responsible for sending and receiving packets.
I tried to test the connection (I run client on one computer and server on another; both create DatagramSocket on the same port) simply by sending "START" string from client to server and after that server should print the string on the console and send back "ACCEPTED", but either client nor server print anything on its console. Could anyone tell me what is going on and why?
Below I show simplified classes (I separated server and client in other packets):
//Client:
public class Client
{
protected static InetAddress serverAddress;
protected static InetAddress clientAdr;
protected static int port;
protected static SingleCom connection;
public static final int PACKET_SIZE = 1024;
public static void main(String[] args) throws IOException, InterruptedException
{
//get server address and port typed from console
load();
connection = new SingleCom();
connection.initilize();
Thread privcastTread = new Thread(connection);
privcastTread.start();
//sending the simplest packet
connection.sendPacket("START", serverAddress);
}
public static synchronized void handlePacket(DatagramPacket packet, String msg) throws IOException
{
if (msg.startsWith("ACCEPTED"))
{
System.out.println("Accepted");
}
}
}
//SingleCom for Client
public class SingleCom implements Runnable
{
DatagramSocket udpSocket;
#Override
public void run()
{
try
{
byte[] buffer = new byte[8192];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
while(true)
{
udpSocket.receive(packet);
String msg = new String(buffer, 0, packet.getLength());
Client.handlePacket(packet, msg);
packet.setLength(buffer.length);
}
}
catch (SocketException e)
{
System.exit(1);
}
catch (IOException e)
{
System.exit(1);
}
}
public void initilize() throws IOException
{
udpSocket = new DatagramSocket(Client.port, InetAddress.getLocalHost());
}
public void sendPacket(String text, InetAddress target) throws IOException
{
byte[] sendedMsg = text.getBytes();
DatagramPacket sendedPacket = new DatagramPacket(sendedMsg, sendedMsg.length, target, Client.port);
udpSocket.send(sendedPacket);
}
public void sendPacket(String text) throws IOException
{
sendPacket(text, Client.serverAddress)
}
public void sendPacket(byte[] content) throws IOException
{
//byte[] sendedMsg = text.getBytes();
DatagramPacket sendedPacket = new DatagramPacket(content, content.length, Client.serverAddress, Client.port);
udpSocket.send(sendedPacket);
}
}
//Server
public class Server
{
protected static InetAddress serverAdr;
protected static InetAddress clientAdr;
protected static SingleCom connection;
protected static int port;
protected static int speed; //in KB/s
private static FileOutputStream fos;
public static void main(String[] args) throws IOException
{
load();
connection = new SingleCom();
connection.initilize();
Thread privcastTread = new Thread(connection);
privcastTread.start();
}
public static synchronized void handlePacket(DatagramPacket pakiet, String msg) throws IOException
{
String[] pieces;
if (msg.startsWith("START"))
{
System.out.println(pieces[0]);
connection.sendPacket("ACCEPTED", clientAdr);
}
}
}
//connection for Server
public class ServerCom implements Runnable
{
DatagramSocket udpSocket;
#Override
public void run()
{
try
{
byte[] buffer = new byte[8192];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
while(true)
{
udpSocket.receive(packet);
String msg = new String(buffer, 0, packet.getLength());
Server.handlePacket(packet, msg);
packet.setLength(buffer.length);
}
}
catch (SocketException e)
{
System.exit(1);
}
catch (IOException e)
{
System.exit(1);
}
}
public void initilize() throws IOException
{
udpSocket = new DatagramSocket(Server.port, InetAddress.getLocalHost());
}
public void sendPacket(String text, InetAddress target) throws IOException
{
byte[] sendedMsg = text.getBytes();
DatagramPacket sendedPacket = new DatagramPacket(sendedMsg, sendedMsg.length, target, Server.port);
udpSocket.send(sendedPacket);
}
public void sendPacket(String text) throws IOException
{
sendPacket(text, Server.clientAdr);
}
}
I need to talk to a C++ application running as a server on a given port. It exposes a binary API(Protocol Buffer) for better performance. My RESTful service is developed in Spring MVC and Jersey and would like to use this new feature. I have been able to consume and produce Protocol Buffer messages successfully.
In my spring web application, I initially created a Apache Commons Pool to create a pool of socket connections. This is how I was reading/writing to the socket
Update 1: Adding PooledObjectFactory implementation
public class PooledSocketConnectionFactory extends BasePooledObjectFactory<Socket> {
private static final Logger LOGGER = LoggerFactory.getLogger(PooledSocketConnectionFactory.class);
final private String hostname;
final private int port;
private PooledSocketConnectionFactory(final String hostname, final int port) {
this.hostname = hostname;
this.port = port;
}
#Override
public Socket create() throws Exception {
return new Socket(hostname, port);
}
#Override
public PooledObject wrap(Socket socket) {
return new DefaultPooledObject<>(socket);
}
#Override
public void destroyObject(final PooledObject<Socket> p) throws Exception {
final Socket socket = p.getObject();
socket.close();
}
#Override
public boolean validateObject(final PooledObject<Socket> p) {
final Socket socket = p.getObject();
return socket != null && socket.isConnected();
}
#Override
public void activateObject(final PooledObject<SocketConnection> p) throws Exception {
}
#Override
public void passivateObject(final PooledObject<SocketConnection> p) throws Exception {
}
}
#Service
#Scope("prototype")
public class Gateway {
#Autowired
private GenericObjectPool pool;
public Response sendAndReceive(Request request) throws CommunicationException {
Response response = null;
final Socket socket = pool.borrowObject();
try {
request.writeDelimitedTo(socket.getOutputStream());
response = Response.parseDelimitedFrom(socket.getInputStream());
} catch (Exception ex) {
LOGGER.error("Gateway error", ex);
throw new CommunicationException("Gateway error", ex);
} finally {
pool.returnObject(socket);
}
return response;
}
}
This works for the first request and when the pool returns any previously used socket it is found that the socket is already closed. This could be because different requests are getting connected to the same input and output streams. If I close the socket after reading the response then it beats the purpose of pooling. If I use a singleton socket and inject it, it is able to process first request and then times out.
If I create the socket on every instance then it works and the performance is around 2500 microseconds for every request. My target is to get the performance within 500 microseconds.
What should be the best approach given the requirements?
Update 2: Adding a server and client
package com.es.socket;
import com.es.protos.RequestProtos.Request;
import com.es.protos.ResponseProtos.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class TcpServer1 {
final static Logger LOGGER = LoggerFactory.getLogger(TcpServer1.class.getName());
public static void main(String[] args) throws Exception {
ServerSocket serverSocket = new ServerSocket(Integer.parseInt(args[0]));
Socket socket = null;
while (true) {
try {
socket = serverSocket.accept();
} catch (IOException e) {
LOGGER.warn("Could not listen on port");
System.exit(-1);
}
Thread thread = new Thread(new ServerConnection1(socket));
thread.start();
}
}
}
class ServerConnection1 implements Runnable {
static final Logger LOGGER = LoggerFactory.getLogger(ServerConnection.class.getName());
private Socket socket = null;
ServerConnection1(Socket socket) {
this.socket = socket;
}
public void run() {
try {
serveRequest(socket.getInputStream(), socket.getOutputStream());
//socket.close();
} catch (IOException ex) {
LOGGER.warn("Error", ex);
}
}
public void serveRequest(InputStream inputStream, OutputStream outputStream) {
try {
read(inputStream);
write(outputStream);
} catch (IOException ex) {
LOGGER.warn("ERROR", ex);
}
}
private void write(OutputStream outputStream) throws IOException {
Response.Builder builder = Response.newBuilder();
Response response = builder.setStatus("SUCCESS").setPing("PING").build();
response.writeDelimitedTo(outputStream);
LOGGER.info("Server sent {}", response.toString());
}
private void read(InputStream inputStream) throws IOException {
Request request = Request.parseDelimitedFrom(inputStream);
LOGGER.info("Server received {}", request.toString());
}
}
package com.es.socket;
import com.es.protos.RequestProtos.Request;
import com.es.protos.ResponseProtos.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.net.Socket;
public class TcpClient1 {
final static Logger LOGGER = LoggerFactory.getLogger(TcpClient1.class.getName());
private Socket openConnection(final String hostName, final int port) {
Socket clientSocket = null;
try {
clientSocket = new Socket(hostName, port);
} catch (IOException e) {
LOGGER.warn("Exception occurred while connecting to server", e);
}
return clientSocket;
}
private void closeConnection(Socket clientSocket) {
try {
LOGGER.info("Closing the connection");
clientSocket.close();
} catch (IOException e) {
LOGGER.warn("Exception occurred while closing the connection", e);
}
}
private void write(OutputStream outputStream) throws IOException {
Request.Builder builder = Request.newBuilder();
Request request = builder.setPing("PING").build();
request.writeDelimitedTo(outputStream);
LOGGER.info("Client sent {}", request.toString());
}
private void read(InputStream inputStream) throws IOException {
Response response = Response.parseDelimitedFrom(inputStream);
LOGGER.info("Client received {}", response.toString());
}
public static void main(String args[]) throws Exception {
TcpClient1 client = new TcpClient1();
try {
Socket clientSocket = null;
LOGGER.info("Scenario 1 --> One socket for each call");
for (int i = 0; i < 2; i++) {
clientSocket = client.openConnection("localhost", Integer.parseInt(args[0]));
OutputStream outputStream = clientSocket.getOutputStream();
InputStream inputStream = clientSocket.getInputStream();
LOGGER.info("REQUEST {}", i);
client.write(outputStream);
client.read(inputStream);
client.closeConnection(clientSocket);
}
LOGGER.info("Scenario 2 --> One socket for all calls");
clientSocket = client.openConnection("localhost", Integer.parseInt(args[0]));
OutputStream outputStream = clientSocket.getOutputStream();
InputStream inputStream = clientSocket.getInputStream();
for (int i = 0; i < 2; i++) {
LOGGER.info("REQUEST {}", i);
client.write(outputStream);
client.read(inputStream);
}
client.closeConnection(clientSocket);
} catch (Exception e) {
LOGGER.warn("Exception occurred", e);
System.exit(1);
}
}
}
Here Request and Response are Protocol Buffer classes. In Scenario 1, it is able to able to process both calls whereas in scenario 2 it never returns from the second read. Seems Protocol Buffer API is handling the streams differently. Sample output below
17:03:10.508 [main] INFO c.d.e.socket.TcpClient1 - Scenario 1 --> One socket for each call
17:03:10.537 [main] INFO c.d.e.socket.TcpClient1 - REQUEST 0
17:03:10.698 [main] INFO c.d.e.socket.TcpClient1 - Client sent ping: "PING"
17:03:10.730 [main] INFO c.d.e.socket.TcpClient1 - Client received status: "SUCCESS"
ping: "PING"
17:03:10.730 [main] INFO c.d.e.socket.TcpClient1 - Closing the connection
17:03:10.731 [main] INFO c.d.e.socket.TcpClient1 - REQUEST 1
17:03:10.732 [main] INFO c.d.e.socket.TcpClient1 - Client sent ping: "PING"
17:03:10.733 [main] INFO c.d.e.socket.TcpClient1 - Client received status: "SUCCESS"
ping: "PING"
17:03:10.733 [main] INFO c.d.e.socket.TcpClient1 - Closing the connection
17:03:10.733 [main] INFO c.d.e.socket.TcpClient1 - Scenario 2 --> One socket for all calls
17:03:10.733 [main] INFO c.d.e.socket.TcpClient1 - REQUEST 0
17:03:10.734 [main] INFO c.d.e.socket.TcpClient1 - Client sent ping: "PING"
17:03:10.734 [main] INFO c.d.e.socket.TcpClient1 - Client received status: "SUCCESS"
ping: "PING"
17:03:10.734 [main] INFO c.d.e.socket.TcpClient1 - REQUEST 1
17:03:10.735 [main] INFO c.d.e.socket.TcpClient1 - Client sent ping: "PING"
After great pain I was able to resolve the issue. The class which was handling the read/write to the socket was defined as prototype. So once a reference to the socket was retrieved it was not cleared up(managed by Tomcat). As such subsequent calls to the socket gets queued up, which then times out and the object is destroyed by Apache Commons Pool.
To fix this, I created class SocketConnection with a ThreadLocal of Socket. On the processing side, I created a Callback to handle read/write to the socket. Sample code snippet below:
class SocketConnection {
final private String identity;
private boolean alive;
final private ThreadLocal<Socket> threadLocal;
public SocketConnection(final String hostname, final int port) throws IOException {
this.identity = UUID.randomUUID().toString();
this.alive = true;
threadLocal = ThreadLocal.withInitial(rethrowSupplier(() -> new Socket(hostname, port)));
}
}
public class PooledSocketConnectionFactory extends BasePooledObjectFactory<SocketConnection> {
private static final Logger LOGGER = LoggerFactory.getLogger(PooledSocketConnectionFactory.class);
final private String hostname;
final private int port;
private SocketConnection connection = null;
private PooledSocketConnectionFactory(final String hostname, final int port) {
this.hostname = hostname;
this.port = port;
}
#Override
public SocketConnection create() throws Exception {
LOGGER.info("Creating Socket");
return new SocketConnection(hostname, port);
}
#Override
public PooledObject wrap(SocketConnection socketConnection) {
return new DefaultPooledObject<>(socketConnection);
}
#Override
public void destroyObject(final PooledObject<SocketConnection> p) throws Exception {
final SocketConnection socketConnection = p.getObject();
socketConnection.setAlive(false);
socketConnection.close();
}
#Override
public boolean validateObject(final PooledObject<SocketConnection> p) {
final SocketConnection connection = p.getObject();
final Socket socket = connection.get();
return connection != null && connection.isAlive() && socket.isConnected();
}
#Override
public void activateObject(final PooledObject<SocketConnection> p) throws Exception {
final SocketConnection socketConnection = p.getObject();
socketConnection.setAlive(true);
}
#Override
public void passivateObject(final PooledObject<SocketConnection> p) throws Exception {
final SocketConnection socketConnection = p.getObject();
socketConnection.setAlive(false);
}
}
class SocketCallback implements Callable<Response> {
private SocketConnection socketConnection;
private Request request;
public SocketCallback() {
}
public SocketCallback(SocketConnection socketConnection, Request request) {
this.socketConnection = socketConnection;
this.request = request;
}
public Response call() throws Exception {
final Socket socket = socketConnection.get();
request.writeDelimitedTo(socket.getOutputStream());
Response response = Response.parseDelimitedFrom(socket.getInputStream());
return response;
}
}
#Service
#Scope("prototype")
public class SocketGateway {
private static final Logger LOGGER = LoggerFactory.getLogger(SocketGateway.class);
#Autowired
private GenericObjectPool<SocketConnection> socketPool;
#Autowired
private ExecutorService executorService;
public Response eligibility(Request request) throws DataException {
EligibilityResponse response = null;
SocketConnection connection = null;
if (request != null) {
try {
connection = socketPool.borrowObject();
Future<Response> future = executorService.submit(new SocketCallback(connection, request));
response = future.get();
} catch (Exception ex) {
LOGGER.error("Gateway error {}");
throw new DataException("Gateway error", ex);
} finally {
socketPool.returnObject(connection);
}
}
return response;
}
}
Try to do some concurrent messaging between the server and the client. When they first connect to eachother and the Server sends the test string, the client gets it perfectly fine the first time. And the client can SEND messages just fine to the Server. But my Client class cant constantly check for messages like my Server can and idk what's wrong. Any suggestions?
Server class code:
import java.lang.*;
import java.io.*;
import java.net.*;
import java.util.Random;
import java.util.concurrent.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Server {
String testMessage = "You are now connected and can begin chatting!";
boolean connected = false;
int port;
public Server(int port) {
this.port = port;
}
public void Open() {
//creates Threadpool for multiple instances of chatting
final ExecutorService clientProcessingPool = Executors.newFixedThreadPool(10);
Runnable serverTask = new Runnable() {
#Override
public void run() {
try {
System.out.println("Opening...");
ServerSocket srvr = new ServerSocket(port);
while (true) {
Socket skt = srvr.accept();
clientProcessingPool.submit(new ClientTask(skt));
}
} catch (Exception e) {
try {
System.out.println(e);
System.out.print("You're opening too many servers in the same location, fool!\n");
ServerSocket srvr = new ServerSocket(port);
while (true) {
Socket skt = srvr.accept();
clientProcessingPool.submit(new ClientTask(skt));
}
} catch (IOException ex) {
Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
};
Thread serverThread = new Thread(serverTask);
serverThread.start();
}
private class ClientTask implements Runnable {
private final Socket skt;
private ClientTask(Socket skt) {
this.skt = skt;
}
#Override
public void run() {
//for sending messages
if (connected == false) {
System.out.println("======================");
System.out.println("Server has connected!");
processMessage(testMessage);
}
//for receiving messages
while (true) {
try {
// Read one line and output it
BufferedReader br = new BufferedReader(new InputStreamReader(skt.getInputStream()));
String incomingMessage = br.readLine();
if (incomingMessage != null) {
System.out.println("Server: Received message: " + incomingMessage);
processMessage(incomingMessage);
}
//br.close();
//skt.close(); //maybe delete
} catch (Exception e) {
System.out.println("Server had error receiving message.");
System.out.println("Error: " + e);
}
}
}
//for processing a message once it is received
public void processMessage(String message) {
PrintWriter out = null;
try {
out = new PrintWriter(skt.getOutputStream(), true);
} catch (IOException ex) {
System.out.println(ex);
System.out.println("Server had error sending message.");
}
System.out.print("Server: Sending message: " + message + "\n");
out.print(message);
out.flush();
connected = true;
try {
skt.shutdownOutput();
//out.close();
} catch (IOException ex) {
Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
Client class code:
import java.lang.*;
import java.io.*;
import java.net.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
class Client {
public String message;
Socket skt;
public int port;
public Client(int port) {
this.port = port;
}
//for receiving messages from Server
public void receiveMessage() {
final ExecutorService clientProcessingPool = Executors.newFixedThreadPool(10);
Runnable serverTask = new Runnable() {
#Override
public void run() {
try {
skt = new Socket(InetAddress.getLocalHost().getHostName(), port);
while (true) {
clientProcessingPool.submit(new Client.ClientTask(skt));
}
} catch (IOException ex) {
Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
}
}
};
Thread serverThread = new Thread(serverTask);
serverThread.start();
}
//for sending messages to Server
public void sendMessage(String outgoingMessage) throws IOException {
try {
skt = new Socket(InetAddress.getLocalHost().getHostName(), port);
PrintWriter pw = new PrintWriter(skt.getOutputStream());
System.out.println("Client: Sending message: " + outgoingMessage);
pw.print(outgoingMessage);
pw.flush();
skt.shutdownOutput();
//skt.close(); //maybe delete
} catch (Exception e) {
System.out.println(e);
System.out.print("Client had error sending message.\n");
JOptionPane.showMessageDialog(null, "That User is not currently online.", "ERROR!!", JOptionPane.INFORMATION_MESSAGE);
}
}
private class ClientTask implements Runnable {
private final Socket skt;
private ClientTask(Socket skt) {
this.skt = skt;
}
#Override
public void run() {
while (true) {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(skt.getInputStream()));
//while (!in.ready()) {}
String incomingMessage = in.readLine();
if (incomingMessage != null) {
System.out.println("Client: Received message: " + incomingMessage); // Read one line and output it
message = incomingMessage;
}
//skt.shutdownInput();
//in.close();
//skt.close(); //maybe delete
} catch (Exception e) {
System.out.print("Client had error receiving message.\n");
}
}
}
}
}
Streams cannot be re-wrapped. Once assigned to a wrapper, they must use that wrapper for the entire life-cycle of the stream. You also shouldn't close a stream until you are done using it, which in this case isn't until your client and server are done communicating.
In your current code, there are a few times where you re-initialize streams:
while (true) {
try {
//Each loop, this reader will attempt to re-wrap the input stream
BufferedReader br = new BufferedReader(new InputStreamReader(skt.getInputStream()));
String incomingMessage = br.readLine();
if (incomingMessage != null) {
System.out.println("Server: Received message: " + incomingMessage);
processMessage(incomingMessage);
}
//don't close your stream and socket so early!
br.close();
skt.close();
} catch (Exception e) {
//...
}
You get the idea; you can use this knowledge to find the stream problems in your client code as well.
With that said, servers are the middle-man between multiple clients. If you want to be able to type in the server's console to send a message to clients, it shouldn't go to only 1 client (unless you had a system that allowed you to specify a name). You need to store every connection in some kind of collection so when you type in the server's console, it goes to every client that's connected. This also helps when a client wants to send a message to every other client (global message). The server's main thread is primarily for accepting clients; I created another thread to allow you to type in the console.
As for your streams, you should create them whenever you start the ClientTask, both server side and client side:
public class Server {
private ExecutorService executor = Executors.newFixedThreadPool(10);
private Set<User> users = new HashSet<>();
private boolean running;
private int port;
public Server(int port) {
this.port = port;
}
public void start() {
running = true;
Runnable acceptor = () -> {
try(ServerSocket ss = new ServerSocket(port)) {
while(running) {
User client = new User(ss.accept());
users.add(client);
executor.execute(client);
}
} catch(IOException e) {
//if a server is already running on this port;
//if the port is not open;
e.printStackTrace();
}
};
Runnable userInputReader = () -> {
try(Scanner scanner = new Scanner(System.in)) {
while(running) {
String input = scanner.nextLine();
for(User user : users) {
user.send(input);
}
}
} catch(IOException e) {
//problem sending data;
e.printStackTrace();
}
};
Thread acceptorThread = new Thread(acceptor);
Thread userThread = new Thread(userInputReader);
acceptorThread.start();
userThread.start();
}
public void stop() {
running = false;
}
public static void main(String[] args) {
new Server(15180).start();
System.out.println("Server started!");
}
}
In the run() method is where the streams should be wrapped.
class User implements Runnable {
private Socket socket;
private boolean connected;
private DataOutputStream out; //so we can access from the #send(String) method
public User(Socket socket) {
this.socket = socket;
}
public void run() {
connected = true;
try(DataInputStream in = new DataInputStream(socket.getInputStream())) {
out = new DataOutputStream(socket.getOutputStream());
while(connected) {
String data = in.readUTF();
System.out.println("From client: "+data);
//send to all clients
}
} catch(IOException e) {
//if there's a problem initializing streams;
//if socket closes while attempting to read from it;
e.printStackTrace();
}
}
public void send(String message) throws IOException {
if(connected) {
out.writeUTF(message);
out.flush();
}
}
}
It's pretty much the same idea with the client:
1. Connect to Server
2. Create "communication" thread
3. Create "user input" thread (to receive input from console)
4. Start threads
public class Client {
private final String host;
private final int port;
private boolean connected;
private Socket socket;
public Client(String host, int port) {
this.host = host;
this.port = port;
}
public void start() throws IOException {
connected = true;
socket = new Socket(host, port);
Runnable serverInputReader = () -> {
try (DataInputStream in = new DataInputStream(socket.getInputStream())) {
while (connected) {
String data = in.readUTF();
System.out.println(data);
}
} catch (IOException e) {
// problem connecting to server; problem wrapping stream; problem receiving data from server;
e.printStackTrace();
}
};
Runnable userInputReader = () -> {
try (DataOutputStream out = new DataOutputStream(socket.getOutputStream());
Scanner scanner = new Scanner(System.in)) {
while (connected) {
String input = scanner.nextLine();
out.writeUTF(input);
}
} catch (IOException e) {
//problem wrapping stream; problem sending data;
e.printStackTrace();
}
};
Thread communicateThread = new Thread(serverInputReader);
Thread userThread = new Thread(userInputReader);
communicateThread.start();
userThread.start();
}
public static void main(String[] args) throws IOException {
new Client("localhost", 15180).start();
}
}
There are a few things I used in the code above that you may not be familiar with. They help simplify the syntax for your code:
Lambda Expressions - Prevents the need to create an anonymous class (or subclass) to declare a method
Try-With-Resources - Closes the resources specified automatically once the try block as ended
EDIT
When a user connects, you should store their connection by name or id. That way, you can send data to specific users. Even if your client is running on the same machine as the server, it's still the same idea: client connects to server, server sends message to client based on name or id:
while(running) {
User client = new User(ss.accept());
users.add(client); //add to set
executor.execute(client);
}
Right now, you are simply adding users to a Set. There is currently no way to grab a specific value from this set. What you need to do is give it some kind of "key". To give you an idea, here's an old algorithm I used to use. I have an array full of empty slots. When someone connects, I look for the first empty slot. Once an empty slot is found, I pass the user the index of the array it's being stored at (that will be the user's id), then store the user in the array at the specified index. When you need to send a message to someone, you can use the id to access that specific array index, grab the user you want and send a message:
class Server {
private int maxConnections = 10;
private ExecutorService executor = Executors.newFixedThreadPool(maxConnections);
private User[] users = new User[maxConnections];
//...
while(running) {
Socket socket = ss.accept();
for(int i = 0; i < users.length; i++) {
if(users[i] == null) {
users[i] = new User(socket, i);
executor.execute(users[i]);
break;
}
}
}
//...
public static void sendGlobalMessage(String message) throws IOException {
for(User user : users)
if(user != null)
user.send(message);
}
public static void sendPrivateMessage(String message, int id) {
User user = users[id];
if(user != null) {
user.send(message);
}
}
}
class User {
private Socket socket;
private int id;
private DataOutputStream out;
public User(Socket socket, int id) {
this.socket = socket;
this.id = id;
}
public void send(String message) throws IOException {
out.writeUTF(message);
out.flush();
}
public void run() {
DataInputStream in;
//wrap in and out streams
while(connected) {
String data = in.readUTF();
//Server.sendGlobalMessage(data);
//Server.sendPrivateMessage(data, ...);
sendMessage(data); //sends message back to client
}
}
}
I have a problem with a multi-connected server TCP. It accepts connection to client, but it stuck when it must read data (array of bytes[]) in InputBuffer.
The code is follow:
Server:
public class thread_acc extends Thread{
private final ServerSocket sock_acc;
public thread_acc() throws IOException {
this.sock_acc = new ServerSocket(10000);
}
#Override
public void run(){
for(;;){
try {
Socket sock_client = sock_acc.accept();
System.out.println("connection accepts");
new Thread(new thread_proc(sock_client)).start();
} catch (IOException ex) { Logger.getLogger(thread_acc.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
public class thread_proc implements Runnable{
private Socket sock_client;
public thread_proc(Socket sock){
this.sock_client = sock;
}
#Override
public void run(){
try {
procRequest();
} catch (IOException ex) {
Logger.getLogger(thread_proc.class.getName()).log(Level.SEVERE, null, ex);
} catch (ClassNotFoundException ex) {
Logger.getLogger(thread_proc.class.getName()).log(Level.SEVERE, null, ex);
}
}
void procRequest() throws IOException, ClassNotFoundException{
byte[] pack1 = socket.readSocket(sock_client);
System.out.println("read pack 1");
byte[] pack2 = socket.readSocket(sock_client);
System.out.println("read pack 2");
.....
}
Client:
public class thread_key implements Runnable {
private static InetAddress IpServer = InetAddress.getByName("127.0.0.1");
private static int PortServer = 10000;
private Socket sock_send;
private int id;
private String namefile;
public thread_key(int id, String namefile) throws IOException {
this.sock_send = new Socket(IpServer, PortServer);
this.id = id;
this.namefile = namefile;
}
#Override
public void run(){
Request();
}
private String[] Request(int iddoc) throws IOException, ClassNotFoundException{
...generations Keys RSA and payloads....
byte[] pack1 = RSA.encryptPub(payload1, pub);
byte[] pack2 = RSA.encryptPub(payload2, pub);
socket.writeSocket(sock_send, pack1);
socket.writeSocket(sock_send, pack2);
System.out.println("write ok");
}
}
Read and Write:
public class socket {
public static void writeSocket(Socket sock, byte[] pacchetto) throws IOException{
ObjectOutputStream out = new ObjectOutputStream(sock.getOutputStream());
out.writeObject(pacchetto);
out.flush();
}
public static byte[] readSocket(Socket sock) throws IOException, ClassNotFoundException{
ObjectInputStream in = new ObjectInputStream(sock.getInputStream());
byte[] pacchetto = (byte[]) in.readObject();
return pacchetto;
}
}
Don't create new object streams every time you want to send or receive something. Use the same streams for the life of the socket, at both ends. Object streams have headers which are read or written on construction, so if construction at the receiver doesn't match construction at the sender, errors will ensue.