I am having a login screen and now say we have 2 users with username:amit and ajay and their password: "pass" and "word".Now i want that suppose their are two desktop applications open on same system.I want that multiple clients access the server concurrently.
Meaning say in one login screen amit enters the username and then his thread should sleep and in second login screen let ajay enter his username then amit will again enter his password after that ajay enter his password.How to do it in java?Please help .
Here I am sharing you a nice Client Server Authentication Application having one server that is communicating with multiple clients using TCP protocol as per your requirement.
Answer:
Here each client is connected in a separate thread from server and that thread contains all the information about the client. It will solve your concurrency problem.
See inline comments for more clarification.
Note: replace host name in LiveChatClient.java file before running this program at port no 1234
Steps to run the program:
First run LiveChatServer only for single time
Then run LiveChatClient for multiple clients as many as you want to add
Here is one more sample in the same context. Please have a look at Java Server with Multiclient communication.
Opcode.java:
Operation code that is used to set a client-server communication protocol
/**************** an interface to define different operation code **************/
public interface Opcode {
int CLIENT_USERNAME = 1;
int CLIENT_INVALID_USERNAME = 2;
int CLIENT_PASSWORD = 3;
int CLIENT_INVALID_PASSWORD = 4;
int CLIENT_CONNECTED = 5;
}
LiveChatServer.java:
Single server that is controlling multiple clients
/************************ Live Chat Server *******************/
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.LinkedHashMap;
public class LiveChatServer {
// Connection state info
private static LinkedHashMap<String, ClientThread> clientInfo = new LinkedHashMap<String, ClientThread>();
// TCP Components
private ServerSocket serverSocket;
// Main Constructor
public LiveChatServer() {
startServer();// start the server
}
public void startServer() {
String port = "1234";
try {
// in constractor we are passing port no, back log and bind address whick will be local
// host
// port no - the specified port, or 0 to use any free port.
// backlog - the maximum length of the queue. use default if it is equal or less than 0
// bindAddr - the local InetAddress the server will bind to
int portNo = Integer.valueOf(port);
serverSocket = new ServerSocket(portNo, 0, InetAddress.getLocalHost());
System.out.println(serverSocket);
System.out.println(serverSocket.getInetAddress().getHostName() + ":"
+ serverSocket.getLocalPort());
while (true) {
Socket socket = serverSocket.accept();
new ClientThread(socket);
}
} catch (IOException e) {
System.out.println("IO Exception:" + e);
System.exit(1);
} catch (NumberFormatException e) {
System.out.println("Number Format Exception:" + e);
System.exit(1);
}
}
public static HashMap<String, ClientThread> getClientInfo() {
return clientInfo;
}
// *********************************** Main Method ********************
public static void main(String args[]) {
new LiveChatServer();
}
}
LiveChatClient.java:
Multiple clients connected to single server
/************************ Live Chat Client *******************/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketException;
public class LiveChatClient {
private String chatName;
private String password;
private String serverAddress;
// TCP Components
private Socket socket;
private BufferedReader in;
private PrintWriter out;
public LiveChatClient() {
initHostName();
runClient();// have fun
}
public void initHostName() {
try {
serverAddress = "<your system name>";
if (serverAddress == null)
System.exit(1);
serverAddress = serverAddress.trim();
if (serverAddress.length() == 0)// empty field
{
System.out.println("Server IP Address or Name can't be blank.");
initHostName();
return;
}
System.out.println("Trying to connect with server...\nServer IP Address:"
+ serverAddress);
// create socket
InetAddress inetAddress = InetAddress.getByName(serverAddress);
if (!inetAddress.isReachable(60000))// 60 sec
{
System.out
.println("Error! Unable to connect with server.\nServer IP Address may be wrong.");
System.exit(1);
}
initPortNo();
} catch (SocketException e) {
System.out.println("Socket Exception:\n" + e);
initHostName();
return;
} catch (IOException e) {
initHostName();
return;
}
}
public void initPortNo() {
try {
String portNo = "1234";
portNo = portNo.trim();
if (portNo.length() == 0)// empty field
{
System.out.println("Server port No can't be blank.");
initPortNo();
return;
}
System.out.println("Trying to connect with server...\nServer Port No:" + portNo);
socket = new Socket(serverAddress, 1234);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);
} catch (IOException e) {
System.out.println("IO Exception:\n" + e);
initPortNo();
return;
}
}
public void sendChatName() throws IOException {
System.out.println("Enter user name:");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String name = br.readLine();
if (name == null)
System.exit(1);
// title case (get only first 9 chars of chat name)
chatName = name.trim();
if (name.length() == 0) {
System.out.println("Please enter user name.");
sendChatName();
return;
}
// sending opcode first then sending chatName to the server
out.println(Opcode.CLIENT_USERNAME);
out.println(chatName);
}
public void sendPassword() throws IOException {
System.out.println("Enter password:");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String name = br.readLine();
if (name == null)
System.exit(1);
// title case (get only first 9 chars of password)
password = name.trim();
if (name.length() == 0) {
System.out.println("Please enter password.");
sendPassword();
return;
}
// sending opcode first then sending password to the server
out.println(Opcode.CLIENT_PASSWORD);
out.println(password);
}
public void runClient() {
try {
sendChatName();
while (true) {
int opcode = Integer.parseInt(in.readLine());
switch (opcode) {
case Opcode.CLIENT_INVALID_USERNAME:
// this client is connecting
System.out.println(chatName + " is invalid user name. Try different one.");
sendChatName();
break;
case Opcode.CLIENT_PASSWORD:
sendPassword();
break;
case Opcode.CLIENT_INVALID_PASSWORD:
// this client is connecting
System.out.println(password + " is invalid password. Try different one.");
sendPassword();
break;
case Opcode.CLIENT_CONNECTED:
System.out.println(chatName + " is connected successfully.");
break;
}
}
} catch (IOException e) {
System.out.println("Client is closed...");
}
}
// *********************************** Main Method ********************
public static void main(String args[]) {
new LiveChatClient();
}
}
ClientThread.java:
Multiple thread started by server one for each client and containing information about all connected clients
/************************ Client Thread *******************/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
public class ClientThread implements Runnable {
// TCP Components
private Socket socket;
private BufferedReader in;
private PrintWriter out;
private String chatName;
private String password;
// seperate thread
private Thread thread;
// boolean variable to check that client is running or not
private volatile boolean isRunning = true;
// opcode
private int opcode;
private static Map<String, String> userpass = new HashMap<String, String>();
static {
userpass.put("amit", "pass");
userpass.put("ajay", "word");
}
public ClientThread(Socket socket) {
try {
this.socket = socket;
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);
thread = new Thread(this);
thread.start();
} catch (IOException e) {
System.out.println(e);
}
}
public void run() {
try {
while (isRunning) {
if (!in.ready())
continue;
opcode = Integer.parseInt(in.readLine());// getting opcode first from client
switch (opcode) {
case Opcode.CLIENT_USERNAME:
chatName = in.readLine();
System.out.println(chatName + " is reqesting to connect.");
boolean result1 = userpass.containsKey(chatName);
if (result1) {
System.out.println(chatName + " is a valid username.");
out.println(Opcode.CLIENT_PASSWORD);
} else {
System.out.println(chatName + " is a invalid username.");
out.println(Opcode.CLIENT_INVALID_USERNAME);
}
break;
case Opcode.CLIENT_PASSWORD:
password = in.readLine();
System.out.println(chatName + " is reqesting to connect having password "
+ password);
boolean result2 = userpass.get(chatName).equals(password);
if (result2) {
System.out.println(password + " is a valid password for username "
+ chatName);
out.println(Opcode.CLIENT_CONNECTED);
} else {
System.out.println(password + " is a invalid password for username "
+ chatName);
out.println(Opcode.CLIENT_INVALID_PASSWORD);
}
break;
}
}
// close all connections
out.close();
in.close();
socket.close();
} catch (IOException e) {
System.out.println(e);
}
}
}
Here is the output when two client are added.
Server:
ServerSocket[addr=computerName/14.98.241.102,port=0,localport=1234]
computerName:1234
abc is reqesting to connect.
abc is a invalid username.
ajay is reqesting to connect.
ajay is a valid username.
ajay is reqesting to connect having password word
word is a valid password for username ajay
amit is reqesting to connect.
amit is a valid username.
amit is reqesting to connect having password word
word is a invalid password for username amit
amit is reqesting to connect having password pass
pass is a valid password for username amit
Client1:(ajay)
Trying to connect with server...
Server IP Address:computerName
Trying to connect with server...
Server Port No:1234
Enter user name:
abc
abc is invalid user name. Try different one.
Enter user name:
ajay
Enter password:
word
ajay is connected successfully.
Client2:(amit)
Trying to connect with server...
Server IP Address:computerName
Trying to connect with server...
Server Port No:1234
Enter user name:
amit
Enter password:
word
word is invalid password. Try different one.
Enter password:
pass
amit is connected successfully.
Use this program as initial starter for your application. Please let me know if you want to add new functionality in the program.
May be you should consider study JavaEE, you are saying is basically is the work that make the servers. Where each client is connect to server to do a login. Now if you need do it 100% desktop in javaSE, you need threads, where each thread will connect to the local login.
JavaEE: http://www.roseindia.net/quickguide/tomcat/Logout.shtml
Threads: http://www.vogella.com/tutorials/JavaConcurrency/article.html
I hope that it helps!!
Related
I have created a Java socket server which creates a socket server on a specified port and then spawns a RecordWriter object to perform some operation on the data stream obtained from each connection.
I start the program with port as 61000 and numthreads as 2.
I also started 3 clients to connect to it.
On the client side I could see that all 3 of them connected to the receiver however, the receiver logs indicated only two of them connected.
netstat -an|grep 61000|grep -i ESTABLISHED
indicated total 6 connections as the client and server are being run on the same machine.
My doubts are:
Why does the client log for the third time show that it could connect to the program on 61000 while I am using the backlog of 2. Also Executors.newFixedThreadPool(numThreads); is allowing only 2 clients to be connected.
Although the server.accept happens in the MyWriter.java and there is no indication in logs that the 3rd client could connect, why does netstat show this as an Established connection
Here are my codes:
MyReceiver.java
package com.vikas;
import java.net.ServerSocket;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class MyReceiver{
protected int serverPort = -1;
protected int numThreads = -1;
protected boolean isStopped = false;
protected Thread runningThread = null;
protected ExecutorService threadPool = null;
protected static Logger logger = LogManager.getLogger(MyReceiver.class);
protected static ServerSocket serverSocket = null;
protected static Map<String, String> mapConnections = new ConcurrentHashMap<String, String>();
public MyReceiver(int port){
this.serverPort = port;
}
public void run(int numThreads){
this.threadPool = Executors.newFixedThreadPool(numThreads);
try {
logger.info("Starting server on port " + this.serverPort);
MyReceiver.serverSocket = new ServerSocket(this.serverPort, numThreads);
} catch (IOException e) {
//throw new RuntimeException("Cannot open port " + this.serverPort, e);
logger.error("Cannot open port " + this.serverPort, e);
}
while(!isStopped()){
this.threadPool.execute(new MyWriter());
}
if(MyReceiver.mapConnections.isEmpty()){
this.threadPool.shutdown();
//System.out.println("Server Stopped after shutdown.") ;
logger.info("Server Stopped after shutdown.");
}
}
public synchronized boolean isStopped() {
return this.isStopped;
}
public synchronized void stop(){
this.isStopped = true;
try {
MyReceiver.serverSocket.close();
} catch (IOException e) {
//throw new RuntimeException("Error closing server", e);
logger.error("Error closing server", e);
}
}
public static void main(String[] args) {
if(args.length != 2){
System.out.println("Number of input arguements is not equal to 4.");
System.out.println("Usage: java -cp YOUR_CLASSPATH -Dlog4j.configurationFile=/path/to/log4j2.xml com.vikas.MyReceiver <port> <number of threads>");
System.out.println("java -cp \"$CLASSPATH:./MyReceiver.jar:./log4j-api-2.6.2.jar:./log4j-core-2.6.2.jar\" -Dlog4j.configurationFile=log4j2.xml com.vikas.MyReceiver 61000 2");
}
int port = Integer.parseInt(args[0].trim());
int numThreads = Integer.parseInt(args[1].trim());
final MyReceiver myConnection = new MyReceiver(port, topic, brokers);
myConnection.run(numThreads);
/*Thread t = new Thread(myConnection);
t.start();*/
try {
Thread.sleep(20000);
} catch (InterruptedException e) {
//e.printStackTrace();
logger.error("Something went wrong", e);
}
//System.out.println("Stopping Server");
Runtime.getRuntime().addShutdownHook(new Thread()
{
#Override
public void run()
{
logger.info("SocketServer - Receive SIGINT!!!");
logger.info("Stopping Server");
if(!myConnection.isStopped()){
myConnection.stop();
}
logger.info("Server Stopped successfully");
try
{
Thread.sleep(1000);
}
catch (Exception e) {}
}
});
//myConnection.stop();
}
}
MyWriter.java
package com.vikas;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.IOException;
import java.net.Socket;
import java.util.Properties;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class MyWriter implements Runnable{
protected String topic = null;
protected String brokers = null;
protected static Logger logger = LogManager.getLogger(MyWriter.class);
public MyWriter () {
}
public void run() {
while(!MyReceiver.serverSocket.isClosed()){
Socket server = null;
try {
server = MyReceiver.serverSocket.accept();
//System.out.println("Just connected to " + server.getRemoteSocketAddress());
logger.info("Just connected to " + server.getRemoteSocketAddress());
MyReceiver.mapConnections.put(server.getRemoteSocketAddress().toString().trim(), "");
//change for prod deployment //change implemented
String key = null;
String message = null;
char ch;
StringBuilder msg = new StringBuilder();
int value = 0;
try {
BufferedReader in = new BufferedReader(new InputStreamReader(server.getInputStream()));
while((value = in.read()) != -1){
ch = (char)value;
if(ch == 0x0a){
//msg.append(ch);
//System.out.println(msg);
message = msg.toString().trim();
//code change as part of testing in prod
if(message.length() != 0){
//do something
msg.setLength(0);
}
else{
logger.error("Blank String received");
msg.setLength(0);
}
}
else{
msg.append(ch);
}
}
logger.info("Closing connection for client :" + server.getRemoteSocketAddress());
//System.out.println("Closing connection for client :" + this.getClientSocket().getRemoteSocketAddress());
server.close();
MyReceiver.mapConnections.remove(server.getRemoteSocketAddress());
} catch (IOException e) {
//report exception somewhere.
//e.printStackTrace();
logger.error("Something went wrong!!", e);
}
finally{
producer.close();
}
} catch (IOException e) {
if(MyReceiver.serverSocket.isClosed()) {
//System.out.println("Server was found to be Stopped.");
logger.error("Server was found to be Stopped.");
logger.error("Error accepting client connection", e);
break;
}
}
}
}
}
The backlog parameter of the ServerSocket constructor restricts the size of the incoming connection queue not the total number of times you are allowed to successfully call accept(). If you want to restrict the number of active connections you need to keep track of how many connections you've accepted then when you hit your threshold don't call accept() again until at least one of the active connections has been closed.
while(!MyReceiver.serverSocket.isClosed()){
Socket server = null;
try {
server = MyReceiver.serverSocket.accept();
//System.out.println("Just connected to " + server.getRemoteSocketAddress());
logger.info("Just connected to " + server.getRemoteSocketAddress());
MyReceiver.mapConnections.put(server.getRemoteSocketAddress().toString().trim(), "");
if (activeConnections == maxConnections) break; // exit accept loop
I've been working on a NIO-based chat application of quite trivial logic: any message sent by any client should be visible to the rest of the users.
Right now, I'm sort of in the middle of the work, I've got pretty complete classes of the clients (and their GUI part) and the server but I've stumbled on a problem I couldn't find any solution on anywhere. Namely, if I run an instance of the server and one instance of the client, in my consoles (one for client, one for the server) I see a nice, expected conversation. However, after adding additional client, this newly created client doesn't get responses from the server - the first still has a valid connection.
I'm not thinking about broadcasting messages to all the clients yet, now I'd like to solve the problem of the lack of proper communication between each of my clients and the server since, I think that broadcasting shouldn't be so big a deal if the communication is fine.
I'd like to also add that I've tried many other ways of instantiating the clients: in one thread, firstly instantiating the clients then applying methods on them, I've event tried using invokeLater from SwingUtilities, since that's the proper way to boot up GUI. Sadly, neither worked.
What should I change to achieve proper communication between clients and the server? What am I doing wrong?
This is the log from client console:
Awaiting message from: client2...
Awaiting message from: client1...
after creating the clients - before any action
1 Message: client1 :: simpleMess1
2 started pushing message from: client1
3 Server response on client side: ECHO RESPONSE: client1 :: simpleMess1
4 Message: client2 :: simpleMessage from c2
5 started pushing message from: client2
6
7 -- No response from client2. AND next try from client2 shows no log at all (!)
8
9 Message: client1 :: simple mess2 from c1
10 started pushing message from: client1
11 Server response on client side: ECHO RESPONSE: client1 :: simpleMess1
And the log from server side console:
1 Server started...
2 S: Key is acceptable
3 S: Key is acceptable
4
5 -- after creating the clients before any action
6 S: Key is readable.
The console output clearly shows that the server receives acceptable keys from both clients but it suggest also that only one SocketChannel has a SelectionKey of readable type, but I've got no clue why. Moreover, I think that the order of creating the clients doesn't matter because as I tested: the client that talks properly with the server is always the one that starts communication as first.
Below I'm posting my Server and Client classes code, hoping You'll Guys help me sort it out.
Firstly, Server class:
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.Set;
public class Server {
private ServerSocketChannel serverSocketChannel = null;
private Selector selector = null;
private StringBuffer messageResponse = new StringBuffer();
private static Charset charset = Charset.forName("ISO-8859-2");
private static final int BSIZE = 1024;
private ByteBuffer byteBuffer = ByteBuffer.allocate(BSIZE);
private StringBuffer incomingClientMessage = new StringBuffer();
Set<SocketChannel> clientsSet = new HashSet<>();
public Server(String host, int port) {
try {
serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.configureBlocking(false);
serverSocketChannel.socket().bind(new InetSocketAddress(host, port));
selector = Selector.open();
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
}
catch (Exception exc) {
exc.printStackTrace();
System.exit(1);
}
System.out.println("Server started...");
serviceConnections();
}
private void serviceConnections() {
boolean serverIsRunning = true;
while (serverIsRunning) {
try {
selector.select();
Set keys = selector.selectedKeys();
Iterator iter = keys.iterator();
while (iter.hasNext()) {
SelectionKey key = (SelectionKey) iter.next();
iter.remove();
if (key.isAcceptable()) {
System.out.println("\tS: Key is acceptable");
SocketChannel incomingSocketChannel = serverSocketChannel.accept();
incomingSocketChannel.configureBlocking(false);
incomingSocketChannel.register(selector, SelectionKey.OP_READ);
clientsSet.add(incomingSocketChannel);
continue;
}
if (key.isReadable()) {
System.out.println("\tS: Key is readable.");
SocketChannel incomingSocketChannel = (SocketChannel) key.channel();
serviceRequest(incomingSocketChannel);
continue;
}
}
}
catch (Exception exc) {
exc.printStackTrace();
continue;
}
}
}
private void serviceRequest(SocketChannel sc) {
if (!sc.isOpen()) return;
incomingClientMessage.setLength(0);
byteBuffer.clear();
try {
while (true) {
int n = sc.read(byteBuffer);
if (n > 0) {
byteBuffer.flip();
CharBuffer cbuf = charset.decode(byteBuffer);
while (cbuf.hasRemaining()) {
char c = cbuf.get();
if (c == '\r' || c == '\n') break;
incomingClientMessage.append(c);
}
}
writeResp(sc, "ECHO RESPONSE: " + incomingClientMessage.toString());
}
}
catch (Exception exc) {
exc.printStackTrace();
try {
sc.close();
sc.socket().close();
}
catch (Exception e) {
}
}
}
private void writeResp(SocketChannel sc, String addMsg)
throws IOException {
messageResponse.setLength(0);
messageResponse.append(addMsg);
messageResponse.append('\n');
ByteBuffer buf = charset.encode(CharBuffer.wrap(messageResponse));
sc.write(buf);
}
//second version - with an attempt to acomlish broadcasting
private void writeResp(SocketChannel sc, String addMsg)
throws IOException {
messageResponse.setLength(0);
messageResponse.append(addMsg);
messageResponse.append('\n');
ByteBuffer buf = charset.encode(CharBuffer.wrap(messageResponse));
System.out.println("clientsSet: " + clientsSet.size());
for (SocketChannel socketChannel : clientsSet) {
System.out.println("writing to: " + socketChannel.getRemoteAddress());
socketChannel.write(buf);
buf.rewind();
}
}
public static void main(String[] args) {
try {
final String HOST = "localhost";
final int PORT = 5000;
new Server(HOST, PORT);
}
catch (Exception exc) {
exc.printStackTrace();
System.exit(1);
}
}
}
and the Client class:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client {
private ClientView clientView;
private String hostName;
private int port;
private String clientName;
private Socket socket = null;
private PrintWriter printWriterOUT = null;
private BufferedReader bufferedReaderIN = null;
public Client(String hostName, int port, String clientName) {
this.hostName = hostName;
this.port = port;
this.clientName = clientName;
initView();
}
public void handleConnection() {
try {
socket = new Socket(hostName, port);
printWriterOUT = new PrintWriter(socket.getOutputStream(), true);
bufferedReaderIN = new BufferedReader(new InputStreamReader(socket.getInputStream()));
waitForIncomingMessageFromClientView();
bufferedReaderIN.close();
printWriterOUT.close();
socket.close();
}
catch (UnknownHostException e) {
System.err.println("Unknown host: " + hostName);
System.exit(2);
}
catch (IOException e) {
System.err.println("I/O err dla");
System.exit(3);
}
catch (Exception exc) {
exc.printStackTrace();
System.exit(4);
}
}
public void initView() {
clientView = new ClientView(clientName);
}
public void waitForIncomingMessageFromClientView() {
System.out.println("Awaiting message from: " + clientName + "...");
while (true) {
if (clientView.isSent) {
System.out.println("Message: " + clientView.getOutgoingMessage());
pushClientViewMessageToServer();
clientView.setIsSent(false);
}
}
}
public void pushClientViewMessageToServer() {
String clientViewMessage = clientView.getOutgoingMessage();
System.out.println("started pushing message from: " + clientView.getClientName());
try {
printWriterOUT.println(clientViewMessage);
String resp = bufferedReaderIN.readLine();
System.out.println("Server response on client side: " + resp);
}
catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Thread thread1 = new Thread(new Runnable() {
#Override
public void run() {
Client c1 = new Client("localhost", 5000, "client1");
c1.handleConnection();
}
});
thread1.start();
Thread thread2 = new Thread(new Runnable() {
#Override
public void run() {
Client c2 = new Client("localhost", 5000, "client2");
c2.handleConnection();
}
});
thread2.start();
}
}
I'll apprecaite any help from You Guys.
EDIT:
the second version of writeResp method attempting to broadcast echo to all the clients produces such log:
Server started...
clientsSet: 2
writing to: /127.0.0.1:63666
writing to: /127.0.0.1:63665
clientsSet: 2
writing to: /127.0.0.1:63666
writing to: /127.0.0.1:63665
It seems like there are two clients and I'm wondering why they don't get proper reply from the server.
while (true) {
int n = sc.read(byteBuffer);
if (n > 0) {
byteBuffer.flip();
CharBuffer cbuf = charset.decode(byteBuffer);
while (cbuf.hasRemaining()) {
char c = cbuf.get();
if (c == '\r' || c == '\n') break;
incomingClientMessage.append(c);
}
}
There is a major problem here. If read() returns -1 you should close the SocketChannel, and if it returns -1 or zero you should break out of the loop.
Write a client application which sets machine time to a given host after that it prints new value
of date. The application uses a standard date at host service which available in TCP port 37.
The arguments are hostname and port number. The default value of port number is 37. If the
program is ran without arguments it communicates with localhost. Program uses standard
output to print information.
Important note:
dateAtHost service gives a signed 32 bit integer with number of seconds since 1st January,
1990.
DateAtHost server
Write a server application which listens on given TCP port and it sends date in 32 bit integer
format to clients like standard date at host service. The program argument is the port number.
The default value of port number is 37. Program uses standard output to print information.
DateAthostclient.java
package DateAthostclient;
import java.net.*;
import java.io.*;
import java.util.*;
public class DateAthostclient {
static final int defaultPort = 37;
static final long offset = 2208988800L;
public static void main(String[] args) {
// TODO code application logic here
int portNumber;
Socket clientSocket;
DataInputStream timeStream;
String hostName;
switch(args.length) {
case 1: hostName = args[0];
portNumber = defaultPort;//dateAtHost Port;
break;
case 2: hostName = args[0];
portNumber = new Integer(args[1]).intValue();
break;
default:
hostName = "localhost";
portNumber = defaultPort;//dateAtHost Port;
}
try {
clientSocket = new Socket(hostName,portNumber);
timeStream = new DataInputStream(clientSocket.getInputStream());
int dateAtHost = timeStream.readInt() + (int)(1L<<32);
new Date().setTime((dateAtHost-offset)*1000);
System.out.println("It is " + new Date().toString() + " at " +hostName);
timeStream.close();
clientSocket.close();
}
catch (UnknownHostException {
System.err.println(" Unknown host error");
}
catch (ConnectException e) {
System.out.println(" Service unavailable on port "+portNumber+"of host "+hostName);
}
catch (IOException e) {
System.err.println(" Communication error occured\r\n "+e);
}
}
}
dayAtHostserver.java
package dayAtHostserver;
import java.net.*;
import java.io.*;
import java.util.*;
public class dayAtHostserver {
public final static int daytimePort = 13;
public static void main(String[] args) {
// TODO code application logic here
ServerSocket theServerSocket;
Socket theConnectionSocket;
PrintWriter out;
try {
theServerSocket = new ServerSocket(daytimePort);
System.out.println("Timeserver ready at port "+daytimePort);
try {
while (true) {
theConnectionSocket = theServerSocket.accept();
System.out.println("Request arrived!");
out = new PrintWriter(theConnectionSocket.getOutputStream(),true);
out.println(new Date());
theConnectionSocket.close();
}
}
catch (IOException e) {
theServerSocket.close();
System.err.println(e);
}
}
catch (IOException e) {
System.err.println(e);
}
}
}
i have two problem
1) i need to understand what is (1L<32) and why he use it here ???
2) when i run server and client date not receive in client
I am trying to establish a TCP connection between a laptop as a client and a pc as a server.
My goal is to use the server to send messages between two android devices. The server has a public IP address. To test the connection, I have written two simple Java classes:
import java.net.ServerSocket;
import java.net.Socket;
public class TcpServer {
public ServerSocket welcome;
public Socket soc;
public int listeningPort = /* default port */;
public TcpServer() {
}
public static void main(String[] args) {
TcpServer ms = new TcpServer();
if(args.length > 0) {
ms.listeningPort = Integer.parseInt(args[0]);
}
ms.listen();
}
public void listen() {
try {
welcome = new ServerSocket(listeningPort);
System.out.println(">>> listening on port " + listeningPort + " <<<");
soc = welcome.accept();
System.out.println(">>> got a new connection from "
+ soc.getInetAddress().toString() + " <<<");
while (true) {
try {
byte b[] = new byte[1024];
soc.getInputStream().read(b, 0, 1);
System.out.print((char) (b[0]));
} catch (Exception e) {
System.err.println(e);
}
}
} catch (Exception e) {
System.err.println(e);
}
}
}
import java.net.Socket;
public class TcpSendClient {
private String serverIp = /* some ip */;
public int port = /* default port */;
private SendThread st;
public TcpSendClient() {
}
public static void main(String[] args) {
TcpSendClient client = new TcpSendClient();
if(args.length > 0) {
client.port = Integer.parseInt(args[0]);
}
client.send();
}
public void send() {
System.out.println("Try to connet to " + serverIp + " via Port" + port);
st = new SendThread(serverIp, port);
st.start();
}
class SendThread extends Thread {
private Socket soc;
public SendThread(String theIp, int thePort) {
try {
soc = new Socket(theIp, thePort);
} catch (Exception e) {
System.err.println(e);
}
}
public void run() {
try {
while (true) {
String toSend = "Hello ";
soc.getOutputStream().write(toSend.getBytes());
Thread.sleep(800);
System.out.println("sent");
}
} catch (Exception e) {
System.err.println(e);
}
}
}
}
When I run both Java files on the server pc, the connection works fine. It also worked if I set up a local Wi-Fi with one laptop and connect to it using another laptop.
But, when I run the client file from a laptop connected to the internet, I am not able to get a connection.
In the firewall on the Server, I opened a number of ports for the connection and the laptop I use as a client has the firewall disabled.
Apart from the firewall, I do not really know what to look into in order to get the connection running. Any ideas as to the cause of my problem and a solution?
I found the solution: The windows firewall was still blocking the ports for Java. It took me a little longer to figure this out, because I was not registered as admin on that pc and could not see the rules.
I'm making a game for an assignment. I have a server and multiclient set up in Java and we're using MVC. I need to have a client send their name to the server and then when two players are present I need to send both names back to the clients along with which player number they are (player one or player two). I don't get how I could tell which thread the information is coming from or which thread the information is getting sent to so not all players think they are player one. Thanks.
Here I am sharing you a nice Chat Program having one server that is communicating with multiple clients using TCP protocol as per your requirement.
Program contains:
Each client is informed wherever a new client is added along with their name and position.
It also checks for existing names. Program doesn't allow multiple clients using same name.
Use this program as initial starter for your game. Please let me know if you want to add new functionality in the program.
Here is the code (see code comments for more clarification):
Note: replace host name in LiveChatClient.java file before running this program at port no 1234
Steps to run the program:
first run LiveChatServer only for single time
then run LiveChatClient for multiple clients as many as you want to add
Opcode.java:
Operation code that is used to set a client-server communication protocol
package com.chat;
/**************** an interface to define different operation code **************/
public interface Opcode {
int CLIENT_CONNECTEING = 1;
int CLIENT_CONNECTED = 2;
}
LiveChatServer.java:
Single server that is controlling multiple clients
package com.chat;
/************************ Live Chat Server *******************/
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.LinkedHashMap;
public class LiveChatServer {
// Connection state info
private static LinkedHashMap<String, ClientThread> clientInfo = new LinkedHashMap<String, ClientThread>();
// TCP Components
private ServerSocket serverSocket;
// Main Constructor
public LiveChatServer() {
startServer();// start the server
}
public void startServer() {
String port = "1234";
try {
// in constractor we are passing port no, back log and bind address whick will be local
// host
// port no - the specified port, or 0 to use any free port.
// backlog - the maximum length of the queue. use default if it is equal or less than 0
// bindAddr - the local InetAddress the server will bind to
int portNo = Integer.valueOf(port);
serverSocket = new ServerSocket(portNo, 0, InetAddress.getLocalHost());
System.out.println(serverSocket);
System.out.println(serverSocket.getInetAddress().getHostName() + ":"
+ serverSocket.getLocalPort());
while (true) {
Socket socket = serverSocket.accept();
new ClientThread(socket);
}
} catch (IOException e) {
System.out.println("IO Exception:" + e);
System.exit(1);
} catch (NumberFormatException e) {
System.out.println("Number Format Exception:" + e);
System.exit(1);
}
}
public static HashMap<String, ClientThread> getClientInfo() {
return clientInfo;
}
// *********************************** Main Method ********************
public static void main(String args[]) {
new LiveChatServer();
}
}
LiveChatClient.java:
Multiple clients talking to each other via server
package com.chat;
/************************ Live Chat Client *******************/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketException;
public class LiveChatClient {
private String chatName;// current user's chat name(max 7 char if greater than show as 6
// char+...
private String serverAddress;
// TCP Components
private Socket socket;
private BufferedReader in;
private PrintWriter out;
public LiveChatClient() {
initHostName();
runClient();// have fun
}
public void initHostName() {
try {
//replace host name with your computer name or IP address
serverAddress = "[hostname]";
if (serverAddress == null)
System.exit(1);
serverAddress = serverAddress.trim();
if (serverAddress.length() == 0)// empty field
{
System.out.println("Server IP Address or Name can't be blank.");
initHostName();
return;
}
System.out.println("Trying to connect with server...\nServer IP Address:"
+ serverAddress);
// create socket
InetAddress inetAddress = InetAddress.getByName(serverAddress);
if (!inetAddress.isReachable(60000))// 60 sec
{
System.out
.println("Error! Unable to connect with server.\nServer IP Address may be wrong.");
System.exit(1);
}
initPortNo();
} catch (SocketException e) {
System.out.println("Socket Exception:\n" + e);
initHostName();
return;
} catch (IOException e) {
initHostName();
return;
}
}
public void initPortNo() {
try {
String portNo = "1234";
portNo = portNo.trim();
if (portNo.length() == 0)// empty field
{
System.out.println("Server port No can't be blank.");
initPortNo();
return;
}
System.out.println("Trying to connect with server...\nServer Port No:" + portNo);
socket = new Socket(serverAddress, 1234);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);
} catch (IOException e) {
System.out.println("IO Exception:\n" + e);
initPortNo();
return;
}
}
public void sendChatName() throws IOException {
System.out.println("Enter your name:");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String name = br.readLine();
if (name == null)
System.exit(1);
// title case (get only first 9 chars of chat name)
name = name.trim();
if (name.equalsIgnoreCase("All")) {
System.out.println("This name is already reserved. Try different one.");
sendChatName();
return;
}
if (name.length() == 0) {
System.out.println("Please enter your chat name.");
sendChatName();
return;
}
if (name.length() == 1)
chatName = String.valueOf(name.charAt(0)).toUpperCase();
if (name.length() > 1 && name.length() < 10)
chatName = String.valueOf(name.charAt(0)).toUpperCase()
+ name.substring(1).toLowerCase();
else if (name.length() > 9)
chatName = String.valueOf(name.charAt(0)).toUpperCase()
+ name.substring(1, 10).toLowerCase();
// sending opcode first then sending chatName to the server
out.println(Opcode.CLIENT_CONNECTEING);
out.println(chatName);
}
public void runClient() {
try {
sendChatName();
while (true) {
int opcode = Integer.parseInt(in.readLine());
switch (opcode) {
case Opcode.CLIENT_CONNECTEING:
// this client is connecting
boolean result = Boolean.valueOf(in.readLine());
if (result) {
System.out
.println(chatName + " is already present. Try different one.");
runClient();
}
break;
case Opcode.CLIENT_CONNECTED:
// a new client is connected
Integer totalClient = Integer.valueOf(in.readLine());
System.out.println("Total Client:" + totalClient);
for (int i = 0; i < totalClient; i++) {
String client = in.readLine();
System.out.println((i + 1) + ":" + client);
}
break;
}
}
} catch (IOException e) {
System.out.println("Client is closed...");
}
}
// *********************************** Main Method ********************
public static void main(String args[]) {
new LiveChatClient();
}
}
ClientThread.java:
Multiple thread started by server one for each client and containing information about all connected clients
package com.chat;
/************************ Client Thread *******************/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.HashMap;
public class ClientThread implements Runnable {
// TCP Components
private Socket socket;
private BufferedReader in;
private PrintWriter out;
private String chatName;
// seperate thread
private Thread thread;
// boolean variable to check that client is running or not
private volatile boolean isRunning = true;
// opcode
private int opcode;
private HashMap<String, ClientThread> clientInfo = new HashMap<String, ClientThread>();
public ClientThread(Socket socket) {
try {
this.socket = socket;
this.clientInfo = LiveChatServer.getClientInfo();
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);
thread = new Thread(this);
thread.start();
} catch (IOException e) {
System.out.println(e);
}
}
public void run() {
try {
while (isRunning) {
if (!in.ready())
continue;
opcode = Integer.parseInt(in.readLine());// getting opcode first from client
switch (opcode) {
case Opcode.CLIENT_CONNECTEING:
chatName = in.readLine();
boolean result = clientInfo.containsKey(chatName);
out.println(Opcode.CLIENT_CONNECTEING);
out.println(result);
if (result)// wait for another chat name if already present
continue;
// send list of already online users to new online user
// for (Object user : clientInfo.keySet().toArray()) {
// out.println(Opcode.CLIENT_CONNECTED);
// out.println(user.toString());
// }
// put new entry in clientInfo hashmap
clientInfo.put(chatName, this);
int i = 0;
for (String key : clientInfo.keySet()) {
if (key.equals(chatName)) {
System.out.println(chatName + " added at " + (i + 1) + " position");
}
i++;
}
// tell other users about new added user and update their online users list
for (ClientThread client : clientInfo.values()) {
client.out.println(Opcode.CLIENT_CONNECTED);
client.out.println(clientInfo.size());
for (ClientThread client1 : clientInfo.values()) {
client.out.println(client1.chatName);
}
}
break;
}
}
// clsoe all connections
out.close();
in.close();
socket.close();
} catch (IOException e) {
System.out.println(e);
}
}
}
Here is the output when two client are added.
Server:
ServerSocket[addr=computerName/IPAddress,port=0,localport=1234]
computerName:1234
Abc added at 1 position
Xyz added at 2 position
Client 1:
Trying to connect with server...
Server IP Address:computerName
Trying to connect with server...
Server Port No:1234
Enter your name:
abc
Total Client:1
1:Abc
Total Client:2
1:Abc
2:Xyz
Client 2:
Trying to connect with server...
Server IP Address:computerName
Trying to connect with server...
Server Port No:1234
Enter your name:
xyz
Total Client:2
1:Abc
2:Xyz
Have 2 threads, one for user 1, and one for user 2. They should communicate to each other using a shared object and notify each other when events occur. Spawn thread 1 when first user connects and spawn thread 2 when second user connects.