How to send messages between two UDP clients? - java

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.

Related

How to group 2 udp clients?

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 don't know how to make it work like described above. Messages are send from client by typing something in console.
server:
public class Server extends Thread{
public final static int PORT = 7331;
private final static int BUFFER = 1024;
private DatagramSocket socket;
private ArrayList<InetAddress> clientAddresses;
private ArrayList<Integer> clientPorts;
private HashSet<String> existingClients;
public Server() throws IOException {
socket = new DatagramSocket(PORT);
System.out.println("[SERVER] UDP server successfully launched on port " + PORT);
clientAddresses = new ArrayList<InetAddress>();
clientPorts = new ArrayList<Integer>();
existingClients = new HashSet<String>();
}
public void run() {
byte[] buf = new byte[BUFFER];
while (true) {
try {
//resets buffer so only new messages get displayed
Arrays.fill(buf, (byte) 0);
DatagramPacket packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
String content = new String(buf, buf.length);
InetAddress clientAddress = packet.getAddress();
int clientPort = packet.getPort();
String id = clientAddress.toString() + "," + clientPort;
if (!existingClients.contains(id)) {
existingClients.add(id);
clientPorts.add(clientPort);
clientAddresses.add(clientAddress);
}
System.out.println(id + " : " + content);
byte[] data = (id + " : " + content).getBytes();
for (int i = 0; i < clientAddresses.size(); i++) {
InetAddress cl = clientAddresses.get(i);
int cp = clientPorts.get(i);
packet = new DatagramPacket(data, data.length, cl, cp);
socket.send(packet);
}
} catch (Exception e) {
System.err.println(e);
}
}
}
public static void main(String args[]) throws Exception {
Server s = new Server();
s.start();
}
}
clients:
public class Client implements Runnable {
public static void main(String args[]) throws Exception {
String host = "127.0.0.1";
DatagramSocket socket = new DatagramSocket();
//handles the receiving part for every client (incoming packets to clients)
MessageReceiver r = new MessageReceiver(socket);
Client s = new Client(socket, host);
Thread rt = new Thread(r);
Thread st = new Thread(s);
rt.start();
st.start();
}
public final static int PORT = 7331;
private DatagramSocket sock;
private String hostname;
Client(DatagramSocket s, String h) {
sock = s;
hostname = h;
}
//sending clients socket to server
private void sendMessage(String s) throws Exception {
//getting bytes from message
byte buf[] = s.getBytes();
//getting hostname from server
InetAddress address = InetAddress.getByName(hostname);
//setting up packet
DatagramPacket packet = new DatagramPacket(buf, buf.length, address, PORT);
//sending packet to server
sock.send(packet);
}
public void run() {
//connected boolean is used to send a greetings message once for every new client that has joined
boolean connected = false;
do {
try {
sendMessage("GREETINGS");
connected = true;
} catch (Exception e) {
}
} while (!connected);
//reads from the console
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
while (true) {
try {
while (!in.ready()) {
Thread.sleep(100);
}
//sends message from console to server
sendMessage(in.readLine());
} catch (Exception e) {
System.err.println(e);
}
}
}
}
//this class handles receiving part of clients
class MessageReceiver implements Runnable {
DatagramSocket sock;
byte buf[];
MessageReceiver(DatagramSocket s) {
sock = s;
buf = new byte[1024];
}
public void run() {
while (true) {
try {
DatagramPacket packet = new DatagramPacket(buf, buf.length);
sock.receive(packet);
String received = new String(packet.getData(), 0,
packet.getLength());
System.out.println(received);
} catch (Exception e) {
System.err.println(e);
}
}
}
}
What youre trying is a message broadcast or a message-repeater-client.
broadcasting is implemented on network layer (using brodcast the local network broadcast adress).
And if you implementing it that way, you'll flood your network, when you have more than 2 clients. Best regards to your network admin. ;-)

Incorrect user delete from list on sever side

I have a small primitive server for studying, and client side.
Here I have piece of my server code:
public class Connector implements Runnable, SocketListener {
private Socket socket;
private ServerSocket serverSocket;
private List<ServerSideClient> clients = new LinkedList<>();
private boolean triger;
public Connector(ServerSocket serverSocket) {
this.serverSocket = serverSocket;
}
#Override
public void run() {
while (true) {
try {
System.out.println("Waiting for clients..");
triger = true;
socket = serverSocket.accept();
System.out.println("Client connected");
ServerSideClient client = createClient();
client.setConnection(true);
client.startListeningClient();
clients.add(client);
new Thread(() -> {
socketIsClosed(client);
}).start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private ServerSideClient createClient() {
return new ServerSideClient(socket);
}
#Override
public synchronized void socketIsClosed(ServerSideClient client) {
while (triger == true) {
if (client.isConnected() == false) {
triger = false;
clients.remove(client);
System.out.println("Client was removed " + clients.size());
}
}
}
}
Here we wait for new Client, then create client instance and add it to LinkedList. In instance on server side we waiting information from client and sending answer on separated thread. But when client closes connection with server, socketIsClosed() method should to delete current client reference from collection. But when client is disconnected I haven't even Logout System.out.println("Client was removed " + clients.size()); from socketIsClosed(ServerSideClient client) method.
Client Code:
public class Client {
private final String HOST = "localhost";
private final int PORT = 1022;
private InputStream inputStream;
private OutputStream outputStream;
private BufferedReader bufferedReader;
private Socket socket;
private boolean connection;
public Client() throws IOException {
socket = new Socket();
socket.connect(new InetSocketAddress(HOST, PORT));
inputStream = socket.getInputStream();
outputStream = socket.getOutputStream();
bufferedReader = new BufferedReader(new InputStreamReader(System.in));
}
public static void main(String[] args) {
Client client = null;
try {
client = new Client();
client.work();
} catch (IOException e) {
e.printStackTrace();
}
}
private void work() {
connection = true;
listenForConsoleInput();
receiveAnswerFromServer();
}
private void listenForConsoleInput() {
new Thread(() -> {
while (connection == true) {
String requset = null;
try {
requset = bufferedReader.readLine();
if (requset.equals(".")) {
closeConnection();
return;
} else {
sendRequest(requset);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
private void sendRequest(String request) {
try {
outputStream.write(request.getBytes());
outputStream.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
private void receiveAnswerFromServer() {
new Thread(() -> {
while (connection == true) {
byte[] data = new byte[32 * 1024];
try {
int numberOfBytes = inputStream.read(data);
System.out.println("Server>> " + new String(data, 0, numberOfBytes));
} catch (IOException e) {
closeConnection();
}
}
}).start();
}
private void closeConnection() {
try {
connection = false;
socket.close();
inputStream.close();
outputStream.close();
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
socketIsClosed(ServerSideClient client) method works in separated thread.
public class ServerSideClient {
private Socket socket;
private InputStream in;
private OutputStream out;
private boolean connection;
private int numOfBytes;
public boolean isConnected() {
return connection;
}
public void setConnection(boolean connection) {
this.connection = connection;
}
public ServerSideClient(Socket socket) {
this.socket = socket;
try {
in = socket.getInputStream();
out = socket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
}
public void startListeningClient() {
new Thread(() -> {
listenUsers();
}).start();
}
private void listenUsers() {
while (connection == true) {
byte[] data = new byte[32 * 1024];
readInputFromClient(data);
if (numOfBytes == -1) {
try {
connection = false;
socket.close();
in.close();
out.close();
isConnected();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Client disconected..");
return;
}
String requestFromClient = new String(data, 0, numOfBytes);
System.out.println("Client sended>> " + requestFromClient);
sendResponce(requestFromClient);
}
}
private void readInputFromClient(byte[] data) {
try {
numOfBytes = in.read(data);
} catch (IOException e) {
e.printStackTrace();
}
}
private void sendResponce(String resp) {
try {
out.write(resp.getBytes());
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I trying to resolve this problem since 2 week, Helllllllp.....
I was able to replicate your problem, and as a easy solution to fix is creating a class SocketClosedListener:
class SocketClosedListener implements Runnable {
private final ServerSideClient client;
private List<ServerSideClient> clients;
public SocketClosedListener(ServerSideClient client, List<ServerSideClient> clients) {
this.client = client;
this.clients = clients;
}
#Override
public void run() {
while (true) {
if (!client.isConnected()) {
clients.remove(client);
System.out.println("Client was removed " + clients.size());
return;
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
And inside your run() method in the Connector class, we have this call:
#Override
public void run() {
while (true) {
try {
System.out.println("Waiting for clients..");
triger = true;
socket = serverSocket.accept();
System.out.println("Client connected");
ServerSideClient client = createClient();
client.setConnection(true);
client.startListeningClient();
clients.add(client);
new Thread(new SocketClosedListener(client, clients)).start();//added
} catch (IOException e) {
e.printStackTrace();
}
}
}
The line added:
new Thread(new SocketClosedListener(client, clients)).start();
It is responsible to be looking for client when disconnected in a separated thread. Also a delay of 100ms to avoid checking each ms that can cause issues when multiple threads running.
With this code I was able to have this in the console:
Waiting for clients..
Client sended>> hi
Client disconected..
Client was removed 1
Client disconected..
Client was removed 0
Okay, I decided this problem with javaRX library. I just used event that send to observer server state. In Observable class I've created:
private PublishSubject<Boolean> subject = PublishSubject.create();
public Observable<Boolean> observable = subject.asObservable();
public void setConnection(boolean connection) {
this.connection = connection;
subject.onNext(this.connection);
}
Method setConnection() set true if client has been connected and false if client initialized disconnect.
In Observer class I initialized an instance of Observable class, and initialized subscription:
client = createClient();
client.observable.subscribe(state -> removeClient(state));
public void removeClient(Boolean state) {
System.out.println("Server state " + state);
if (state == false) {
clients.remove(client);
System.out.println("Client remowed. List size: " + clients.size());
}
}
Now, I always know about server state, and make client removing if last has initialized disconnection.

Java SocketServer Connected to a AccessGuard 1000 Solution

I have the following issue connecting to a AccessGard (newnet) solution that forwards TPC messages to my application from a POS.
Basically the AG automatically connects from an ip "X.X.X.2" to my pooled server but it never sends any data.
When the POS send the message for some reason the AG sends the TPC request from another IP "X.X.X.132" but it never triggers the serverSocket.accept()
With wiresharck I can see Keep Alive messages from the X.X.X.2 to my server every second. Also I can see the request incoming from ip "X.X.X.132" but it never reaches the server. All the incoming transmissions come to the same port.
here is my server :
public class Server2 {
protected int serverPort = 8005;
protected ServerSocket serverSocket = null;
protected boolean isStopped = false;
protected Thread runningThread= null;
protected ExecutorService threadPool = Executors.newFixedThreadPool(10);
public Server2()
{}
public void run(){
openServerSocket();
while(! isStopped()){
Socket clientSocket = null;
try {
clientSocket = this.serverSocket.accept();
} catch (IOException e) {
if(isStopped()) {
System.out.println("Server Stopped.") ;
break;
}
throw new RuntimeException(
"Error accepting client connection", e);
}
this.threadPool.execute(
new WorkerRunnable(clientSocket,
"Thread Pooled Server"));
}
this.threadPool.shutdown();
System.out.println("Server Stopped.") ;
}
private void openServerSocket() {
try {
this.serverSocket = new ServerSocket(this.serverPort);
} catch (IOException e) {
throw new RuntimeException("Cannot open port 8005", e);
}
}
private synchronized boolean isStopped() {
return this.isStopped;
}
}
here the worker:
public class WorkerRunnable implements Runnable
{
private static final Logger logger = Logger.getLogger(WorkerRunnable.class);
protected Socket connectionSocket = null;
protected String serverText = null;
public WorkerRunnable(Socket connectionSocket, String serverText) {
this.connectionSocket = connectionSocket;
this.serverText = serverText;
}
public void run() {
try {
System.out.println(read());
} catch (IOException e) {
//report exception somewhere.
e.printStackTrace();
}
}
private String read() throws IOException
{
InputStream in = connectionSocket.getInputStream();
byte[] m = new byte[2];
in.read(m,0,2);
ByteBuffer wrapped = ByteBuffer.wrap(m);
short num = wrapped.getShort();
logger.info("IN message length:" + num +" Hexa:" + String.format("%02x", m[0]) + String.format("%02x", m[1])); System.out.println("IN message length:" + num +" Hexa:" + String.format("%02x", m[0]) + String.format("%02x", m[1]));
byte[] message = new byte[num];
in.read(message,0,num);
String inMessage = Util.bytesToHex(message);
logger.info("Full message:" + inMessage); System.out.println("Full message:" + inMessage );
return inMessage;
}
}

How do you connect a DatagramSocket server and client outside of a local area network(LAN)?

I am able to connect my DatagramSocket server and client inside my local area network(LAN) but I am unable outside of it.
Here is my code:
GameServer class:
public class GameServer extends Thread {
private DatagramSocket socket;
public GameServer() {
try {
this.socket = new DatagramSocket(7081,InetAddress.getByName("0.0.0.0"));
} catch (Exception e) {
e.printStackTrace();
}
}
public void run() {
while (true) {
byte[] data = new byte[1024];
DatagramPacket packet = new DatagramPacket(data, data.length);
try {
socket.receive(packet);
if(new String(packet.getData()).trim().equalsIgnoreCase("ping")){
sendData("pong".getBytes(),packet.getAddress(),packet.getPort());
}
System.out.println(new String(packet.getData()));
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void sendData(byte[] data, InetAddress ipAddress, int port) {
DatagramPacket packet = new DatagramPacket(data, data.length, ipAddress, port);
try {
this.socket.send(packet);
} catch (IOException e) {
e.printStackTrace();
}
}
}
GameClient class:
public class GameClient extends Thread {
private InetAddress ipAddress;
private DatagramSocket socket;
public GameClient(String ipAddress) {
try {
this.socket = new DatagramSocket();
this.ipAddress = InetAddress.getByName(ipAddress);
} catch (SocketException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
public void run() {
while (true) {
byte[] data = new byte[1024];
DatagramPacket packet = new DatagramPacket(data, data.length);
try {
socket.receive(packet);
System.out.println(new String(packet.getData()));
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void sendData(byte[] data) {
DatagramPacket packet = new DatagramPacket(data, data.length, ipAddress, 7081);
try {
socket.send(packet);
} catch (IOException e) {
e.printStackTrace();
}
}
}
RunClient class:
public class RunClient {
public static void main(String[] args) {
GameClient client = new GameClient("/*Here is my external ip address*/"); //If i am running this for LAN then 192.168.1.67 and localhost work
client.start();
client.sendData("ping".getBytes());
}
}
RunServer class:
public class RunServer {
public static void main(String[] args) {
GameServer server = new GameServer();
server.start();
}
}
Here are my port forwarding configurations:
Some additional information:
My local ip address is 192.168.1.67
The port I am using is 7081
When I check my ip and port at http://www.canyouseeme.org it gave me the following error:
Error: I could not see your service on "my external ip" on port (7081)
I don't see any problem in your code. That site (http://www.canyouseeme.org) must be trying with TCP instead of UDP.
Please add exception for the port 7081 into firewall, so that it allow incoming connections on port.
when you are trying in LAN the IP might be different, when you are trying outside, you have to try with the external ip, which should be configured to redirect the request to your localip.
Thanks,
Ankireddy Polu

Java Socketing: My server class constantly takes in input but my client doesn't?

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
}
}
}

Categories