i know there is alot of post that ask how to comunicate between client and server ,but in the majority those are generally people using the localhost, I have for project to use a vps and several client computer, unfortunately all the solutions given in the other post does not work, indeed the client does not seem to be able to connect to my vps
there is my client code
public IRCClient() throws IOException {
socket = new Socket(InetAddress.getByAddress(new byte[]{(byte) 185, (byte) 242, (byte) 180,97}), 2406);
messages = new LinkedBlockingQueue<Object>();
server = new ConnectionToServer(socket);
Thread messageHandling = new Thread() {
public void run() {
while (true) {
try {
Object message = messages.take();
parse(message);
System.out.println("Message Received: " + message);
} catch (InterruptedException e) {
}
}
}
};
messageHandling.setDaemon(true);
messageHandling.start();
}
private void parse(Object message) {
String msg = String.valueOf(message);
if (msg.contains("-")) {
if (msg.contains("key")) {
key = msg.split("-")[1];
} else if (msg.contains("name")) {
name = msg.split("-")[1];
} else if (msg.contains("world")) {
world = msg.split("-")[1];
} else if (msg.contains("server")) {
serverName = msg.split("-")[1];
} else if (msg.contains("x")) {
x = Integer.parseInt(msg.split("-")[1]);
} else if (msg.contains("y")) {
y = Integer.parseInt(msg.split("-")[1]);
} else if (msg.contains("z")) {
z = Integer.parseInt(msg.split("-")[1]);
} else if (msg.contains("isEntity")) {
entity = msg.split("-")[1].equalsIgnoreCase("true");
} else if (msg.contains("ticks")) {
lTicks = Integer.parseInt(msg.split("-")[1]);
} else if (msg.contains("end")) {
if (key.equalsIgnoreCase(MultiPingMod.getKey()) && !name.equalsIgnoreCase(Minecraft.getMinecraft().thePlayer.getName())) {
MultiPing m = new MultiPing(name, world, serverName, x, y, z, entity);
MultiPingMod.setTime(lTicks);
m.render = true;
if (MultiPingMod.render.getToRender().containsKey(name)) {
MultiPingMod.render.getToRender().get(name).render = false;
MultiPingMod.render.getToRender().remove(name);
}
MultiPingMod.render.addToRender(m);
}
}
}
}
public void send(Object obj) {
server.write(obj);
}
private class ConnectionToServer {
ObjectInputStream in;
ObjectOutputStream out;
Socket socket;
ConnectionToServer(Socket socket) throws IOException {
this.socket = socket;
in = new ObjectInputStream(socket.getInputStream());
out = new ObjectOutputStream(socket.getOutputStream());
Thread read = new Thread() {
public void run() {
while (true) {
try {
Object obj = in.readObject();
messages.put(obj);
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
};
read.setDaemon(true);
read.start();
}
private void write(Object obj) {
try {
out.writeObject(obj);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
i got this code from somewhere in this forum because after lot of attempt nothing was working
same for the server code here is :
public ServerListener() {
debug("Creating the server");
clientList = new ArrayList<ConnectionToClient>();
messages = new LinkedBlockingQueue<Object>();
debug("Client list is created");
try {
serverSocket = new ServerSocket(2406);
debug("opening the port 2406");
} catch (IOException e) {
e.printStackTrace();
debug(e.getMessage());
}
debug("creating the accept thread");
Thread accept = new Thread() {
public void run() {
debug("thread created");
while (true) {
try {
Socket s = serverSocket.accept();
if(s!=null) {
debug("new client joined");
clientList.add(new ConnectionToClient(s));
debug("new client was accepted ["+ s.getInetAddress() + "/" + s.getPort()+"]");
}
} catch (IOException e) {
e.printStackTrace();
debug(e.getMessage());
}
}
}
};
accept.setDaemon(true);
accept.start();
Thread messageHandling = new Thread() {
public void run() {
while (true) {
try {
Object message = messages.take();
debug("we parse the ping");
parse(message);
System.out.println("Message Received: " + message);
} catch (InterruptedException e) {
}
}
}
};
messageHandling.setDaemon(true);
messageHandling.start();
}
private void parse(Object message) {
String msg = String.valueOf(message);
if(msg.contains("-")) {
if(msg.contains("key")) {
debug("key detected");
key = msg.split("-")[1];
} else if(msg.contains("name")) {
debug("name detected");
name = msg.split("-")[1];
} else if(msg.contains("world")) {
debug("worldname detected");
world = msg.split("-")[1];
} else if(msg.contains("server")) {
debug("servername detected");
server = msg.split("-")[1];
} else if(msg.contains("x")) {
debug("x detected");
x = Integer.parseInt(msg.split("-")[1]);
} else if(msg.contains("y")) {
debug("y detected");
y = Integer.parseInt(msg.split("-")[1]);
} else if(msg.contains("z")) {
debug("z detected");
z = Integer.parseInt(msg.split("-")[1]);
} else if(msg.contains("isEntity")) {
debug("entity detected");
entity = msg.split("-")[1].equalsIgnoreCase("true");
} else if(msg.contains("ticks")) {
debug("ticks detected");
lTicks = Integer.parseInt(msg.split("-")[1]);
} else if(msg.contains("end")) {
debug("we got everything detected");
toSend = new IrcMPING(key, name, world, server, x, y, z, entity, lTicks);
for(String str : toSend.getArgs()) {
sendToAll(str);
}
toSend=null;
}
}
}
public void sendToOne(int index, Object message) throws IndexOutOfBoundsException {
clientList.get(index).write(message);
}
public void sendToAll(Object message) {
for (ConnectionToClient client : clientList) {
debug("sending the ping to " + client.socket.getInetAddress());
client.write(message);
}
}
public void debug(String str) {
System.out.println("SOROS DEBUG [MULTIPING] : " + str) ;
}
private class ConnectionToClient {
ObjectInputStream in;
ObjectOutputStream out;
Socket socket;
ConnectionToClient(Socket socket) throws IOException {
this.socket = socket;
in = new ObjectInputStream(socket.getInputStream());
out = new ObjectOutputStream(socket.getOutputStream());
Thread read = new Thread() {
public void run() {
while (true) {
try {
Object obj = in.readObject();
messages.put(obj);
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
};
read.setDaemon(true); // terminate when main ends
read.start();
}
public void write(Object obj) {
try {
out.writeObject(obj);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
i run the jar from the vps (who is based on debian) using the java jar command , but nothing to do i only get this on the terminal
https://cdn.discordapp.com/attachments/832578338567487497/833752196017029170/unknown.png //link to the image
How can i do to make this work ? there is any other way than socket to make two jar communicate from distant computer/server ? thank you for reading me and thank you if you try to help me
Related
I want to transfer objects (AssignmentListener) from one Java Server to 5 Java Clients.
Therefore I wrote a method to send out the message:
private void sendMessage(AssignmentListener listener, int[] subpartitionIndices){
boolean success = false;
int failCount = 0;
// retry for the case of failure
while(!success && failCount < 10) {
try {
// get the stored socket & stream if stored
if(listener.getSocket() == null) {
if (localMode) {
listener.setSocket(new Socket("localhost", listener.getPort()));
} else {
listener.setSocket(new Socket(listener.getIp(), listener.getPort()));
}
listener.setOutputStream(new ObjectOutputStream(listener.getSocket().getOutputStream()));
}
AssignmentListenerMessage assignmentListenerMessage = new AssignmentListenerMessage(subpartitionIndices);
System.out.println("Sending " + assignmentListenerMessage);
listener.getOutputStream().writeObject(assignmentListenerMessage);
listener.getOutputStream().flush();
success = true;
} catch (IOException se) {
se.printStackTrace();
System.err.println("Failed to forward " + Arrays.toString(subpartitionIndices) + " to " + listener);
failCount++;
}
}
}
On the client side, I have the following:
public void run() {
String mode = "remote";
if(localMode) mode = "local";
// we need to register this listener at at the OverpartitioningManager
if(register(isLocalRequest)) System.out.println("Registered AssignmentListenerServer for index "+subpartitionIndex+" at ForwardingServer - "+mode);
running = true;
while (running) {
try {
socket = serverSocket.accept();
// Pass the socket to the RequestHandler thread for processing
RequestHandler requestHandler = new RequestHandler( socket );
requestHandler.start();
} catch (SocketException se) {
se.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
class RequestHandler extends Thread {
private Socket socket;
RequestHandler(Socket socket) {
this.socket = socket;
}
#Override
public void run() {
try {
System.out.println("Received a connection");
// Get input and output streams
inStream = new ObjectInputStream(socket.getInputStream());
//outStream = new DataOutputStream(socket.getOutputStream());
AssignmentListenerMessage incomingMessage = null;
while(socket.isBound()) {
try {
incomingMessage = (AssignmentListenerMessage) inStream.readObject();
}catch (StreamCorruptedException sce){
System.out.println("Failed to read AssignmentMessage from Stream, but will try again... (no ack)");
sce.printStackTrace();
continue;
}
// do stuff with the message
}
// Close our connection
inStream.close();
socket.close();
System.out.println("Connection closed");
} catch (Exception e) {
e.printStackTrace();
}
}
}
This works multiple times, but at one point I get the following exception:
java.io.StreamCorruptedException: invalid type code: 00
Does anyone have an idea or any other performance improvement for what I'm doing?
Thanks.
I have a multithreaded tcp server, that handles multiple clients.
Each client has its thread on the serverside that keeps the socket connection.
Everything theoretically works fine for many minutes, but at rare occasions, while having multiple clients connected, the following happens:
One of the clients sends a tcp packet to the server and the serverside read times out. I have found many questions, that tackle read timeouts on the clientside, but in my case, this never happens. In my case, the server times out on a read when receiving a packet from a client.
My question is, why and how can this happen and what can I do to handle this problem?
here is my server listener:
public class GameServerTCP extends Thread {
//TCP
private ServerSocket serverSocket;
public Server server;
public int amountOfTCPConnections = 0;
ClassLoader classLoader = getClass().getClassLoader();
File myFile = new File(classLoader.getResource("Sprites/sprite_sheet.png").getFile());
public GameServerTCP(Server game) {
this.server = game;
//TCP
try {
serverSocket = new ServerSocket(6336);
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
while(true) {
//TCP
Socket socket = null;
try {
socket = serverSocket.accept();
Toolkit.getDefaultToolkit().beep();
System.out.println(socket.getRemoteSocketAddress() + " has connected to server.");
}
catch (Exception e) {
e.printStackTrace();
}
new TCPConnection(socket, this);
amountOfTCPConnections++;
if (amountOfTCPConnections > 500) {
System.err.println("Too many clients error! (unsolved)");
server.frame.dispatchEvent(new WindowEvent(server.frame, WindowEvent.WINDOW_CLOSING));
}
}
}
}
here is my server thread that hold each single connection:
public class TCPConnection implements Runnable {
Socket socket;
private Thread thread;
private boolean isRunning = false;
public GameServerTCP serverTCP;
private String gamename = "-1";
public String username;
/**
* This is the future!
* Contains an exact imprint of the player of client side.
* Cheats can be detected here.
*/
private PlayerMP playerMP;
String clientSentence;
TCPConnection(Socket socket, GameServerTCP serverTCP) {
this.socket = socket;
this.serverTCP = serverTCP;
isRunning = true;
thread = new Thread(this);
thread.start();
}
public synchronized void closeConnection() {
if (MasterConnections.connectionsTCP.containsKey(getUniqueConnectionIdentifier())) MasterConnections.connectionsTCP.remove(getUniqueConnectionIdentifier());
if (this.username != null && MasterConnections.currentlyLoggedOnAccounts.contains(this.username)) MasterConnections.currentlyLoggedOnAccounts.remove(this.username);
if (this.gamename != null && serverTCP.server.games.containsKey(this.gamename)) {
Level game = serverTCP.server.games.get(this.gamename);
for (String p : game.playersInLevel) {
if (p.equals(getUniqueConnectionIdentifier())) {
game.playersInLevel.remove(p);
System.out.println(this.username + " has been been removed from game " + this.gamename + ".");
}
}
PacketTCP02LeaveGame tellOthersPacket = new PacketTCP02LeaveGame(this.gamename, this.username);
game.writeDataTCPToAllPlayersInThisLevel(tellOthersPacket);
}
try {
this.socket.close();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(socket.getRemoteSocketAddress() + " has been disconnected from server.");
this.serverTCP.amountOfTCPConnections--;
this.stop();
}
public String getUniqueConnectionIdentifier() {
return socket.getInetAddress() + ":" + socket.getPort();
}
public String generateUniqueUDPConnectionIdentifier(InetAddress inetAddess, int udpPort) {
System.out.println("uuc created: ");
System.out.println(inetAddess + "/" + udpPort);
return inetAddess + ":" + udpPort;
}
public void run() {
//version check first
PacketTCP00VersionCheck packetVersionCheck = new PacketTCP00VersionCheck(serverTCP.server.getVersion());
if (MasterConnections.connectionsTCP.containsKey(getUniqueConnectionIdentifier())) {
this.closeConnection();
}
else {
MasterConnections.connectionsTCP.put(getUniqueConnectionIdentifier(), this);
packetVersionCheck.writeData(this);
}
BufferedReader inFromClient;
try {
inFromClient = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (IOException e1) {
e1.printStackTrace();
closeConnection();
return;
}
while(isRunning) {
try {
clientSentence = inFromClient.readLine();
if (clientSentence == null) {
inFromClient.close();
closeConnection();
}
else {
System.out.println("tcprec -> " + (new Date(System.currentTimeMillis())) + " -> " + this.username + " -> " + clientSentence);
this.parsePacket(clientSentence.getBytes());
}
}
catch (SocketTimeoutException ste) {
/**
* TODO:
*/
ste.printStackTrace();
System.err.println("YOU CAN DO SOMETHING HERE!!!!!!!");
closeConnection();
}
catch (Exception e) {
e.printStackTrace();
closeConnection();
}
}
}
public void stop() {
isRunning = false;
try {
thread.join();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
And here is my client:
public class GameClientTCP extends Thread {
public String gamestate = "logged out";
private Game game;
public Socket tcpSocket;
public boolean isRunning = false;
private String serverSentence;
public boolean hasBeenStarted = false;
public int boundUDPPort = -1;
public static String[] characters = new String[5];
public static boolean charactersAreLoaded = false;
private PrintWriter toServer;
public GameClientTCP(Game game, String ipAddress) {
this.game = game;
}
public boolean tryConnect() {
try {
tcpSocket = new Socket();
tcpSocket.connect(new InetSocketAddress(Settings.SERVER_ADDRESS, 6336), 1000);
System.out.println("Just connected to " + tcpSocket.getRemoteSocketAddress());
game.getSocketClientUDP().prepareBeforeStart();
game.getSocketClientUDP().start();
return true;
} catch (UnknownHostException e1) {
try {
tcpSocket.close();
} catch (IOException e) {
GameError.appendToErrorLog(e);
return false;
}
return false;
} catch (IOException e1) {
try {
tcpSocket.close();
} catch (IOException e) {
GameError.appendToErrorLog(e);
return false;
}
GameError.appendToErrorLog(e1);
return false;
}
}
public void run() {
BufferedReader fromServer;
try {
fromServer = new BufferedReader(new InputStreamReader(tcpSocket.getInputStream()));
toServer = new PrintWriter(tcpSocket.getOutputStream(),true);
} catch (IOException e1) {
GameError.appendToErrorLog(e1);
return;
}
while(isRunning) {
try {
serverSentence = fromServer.readLine();
//System.out.println("Received: " + serverSentence);
if (serverSentence != null) this.parsePacket(serverSentence.getBytes());
}
catch(UnknownHostException ex) {
GameError.appendToErrorLog(ex);
}
catch(IOException e){
GameError.appendToErrorLog(e);
}
catch(Exception e) {
GameError.appendToErrorLog(e);
}
}
}
public void sendMessageToServer(String message) {
try {
toServer.println(message);
toServer.flush();
}
catch (Exception e) {
GameError.appendToErrorLog(e);
System.exit(-1);
}
}
}
I hope to find out more about this issue, please help! :)
EDIT: It may be important to say, that while my program is running, it can occur, that there are no tcp packets sent over a longer period of time. The timeout always happens, when i dont send any packets for at least 20 or 30 minutes and then when i send one again, another client times out.
As it turned out, tcp sockets, that are not used longer than a certain amount of time will be kind of destroyed by peers and therefore lose their connection.
I solved my issue, by sending a nearly empty tcp packet every minute to make it clear to all programs and services, that these sockets are alive!
A few days ago i tried to create a server - client or client Server as an experiment to learn about socket using a thread but then someone told me that i should use swingWorker. I did some research how to use and have implemented it in as practice but it still doesn't work. the swingWorker thread doesn't look like it is running even tho i get a connection and have used .excute(). If you guys can help spot where i am doing wrong that will be great. SwingWorker class is in the startSever() and startClient() method.
private void startServer() {
SwingWorker <Void, String> runningServer = new SwingWorker<Void, String>(){
protected Void doInBackground() {
try {
listeningSocket = new ServerSocket(port);
System.out.println("waiting for connection");
connection = listeningSocket.accept();
connected = true;
System.out.println("Connected");
String incomeMessage =null;
while(connected){
inStream = connection.getInputStream();
inDataStream = new DataInputStream(inStream);
if (myMessage !=null){
outStream = connection.getOutputStream();
outDataStream = new DataOutputStream(outStream);
outDataStream.writeUTF(myMessage);
}
if((incomeMessage = inDataStream.readUTF())!=null){
clientMessage = incomeMessage;
publish(clientMessage);
incomeMessage =null;
}
}
} catch (IOException e) {
clientMessage = "Connection Lost";
}
return null;
}
runningServer.execute();
}
Here's a VERY basic example.
Basically, because you program requires asynchronous communications (that is, you need to be able to read from the socket AND write to it at the same time), you need to offload each stream to a separate thread.
The management process of this example is, well, no existent. Realistically, you should have some kind of "connection" manager that would be able to cleanly close the output and input threads so that, for example, when the user types "bye", the output thread would be able to tell the connection manager that the connection should be terminated. It would then tell the input thread to stop reading any new message and terminate...
Client
public class Client {
public static void main(String[] args) {
try {
Socket master = new Socket("localhost", 8900);
new Thread(new InputHandler(master)).start();
new Thread(new OuputHandler(master)).start();
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static class InputHandler implements Runnable {
private Socket socket;
public InputHandler(Socket socket) {
this.socket = socket;
}
#Override
public void run() {
boolean commune = true;
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while (commune) {
String text = reader.readLine();
System.out.println("\n<server> " + text);
if (text.toLowerCase().equals("bye")) {
commune = false;
}
}
} catch (Exception exp) {
exp.printStackTrace();
} finally {
try {
reader.close();
} catch (Exception e) {
}
try {
socket.close();
} catch (Exception e) {
}
}
}
}
public static class OuputHandler implements Runnable {
private Socket socket;
public OuputHandler(Socket socket) {
this.socket = socket;
}
#Override
public void run() {
boolean commune = true;
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
Scanner scanner = new Scanner(System.in);
while (commune) {
System.out.print("> ");
String text = scanner.nextLine();
writer.write(text);
writer.newLine();
writer.flush();
if (text.equalsIgnoreCase("bye")) {
commune = false;
}
}
} catch (Exception exp) {
exp.printStackTrace();
} finally {
try {
writer.close();
} catch (Exception e) {
}
try {
socket.close();
} catch (Exception e) {
}
}
}
}
}
Server
public class Server {
public static void main(String[] args) {
try {
ServerSocket master = new ServerSocket(8900);
Socket socket = master.accept();
new Thread(new InputHandler(socket)).start();
new Thread(new OuputHandler(socket)).start();
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static class InputHandler implements Runnable {
private Socket socket;
public InputHandler(Socket socket) {
this.socket = socket;
}
#Override
public void run() {
boolean commune = true;
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while (commune) {
String text = reader.readLine();
System.out.println("\n<client> " + text);
if (text.toLowerCase().equals("bye")) {
commune = false;
}
}
} catch (Exception exp) {
exp.printStackTrace();
} finally {
try {
reader.close();
} catch (Exception e) {
}
try {
socket.close();
} catch (Exception e) {
}
}
}
}
public static class OuputHandler implements Runnable {
private Socket socket;
public OuputHandler(Socket socket) {
this.socket = socket;
}
#Override
public void run() {
boolean commune = true;
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
Scanner scanner = new Scanner(System.in);
while (commune) {
System.out.print("> ");
String text = scanner.next();
writer.write(text);
writer.newLine();
writer.flush();
if (text.equalsIgnoreCase("bye")) {
commune = false;
}
}
} catch (Exception exp) {
exp.printStackTrace();
} finally {
try {
writer.close();
} catch (Exception e) {
}
try {
socket.close();
} catch (Exception e) {
}
}
}
}
}
Update (whine)
While I have your source code in front of me...
There should very, very, rarely be a need to do textMessage.addKeyListener(this)
Because you are using a JTextField, you should be using a ActionListener instead. There are a a number of important reasons for this, but for you, the main one would be the fact that a "accept" action is Look and Feel dependent. While most systems do use Enter as there "accept" action, is not a guarantee.
Have a look at How to Write a Action Listener for more information
Given the general complexity of what you are trying to do, +1 for a overall good attempt!
Using this example, the following changes work with a single telnet client.
private PrintWriter out;
...
public void keyPressed(KeyEvent e) {
if (e.getKeyChar() == KeyEvent.VK_ENTER) {
myMessage = friendLabel + textMessage.getText();
if (out != null) {
out.println(myMessage);
}
...
}
...
protected Void doInBackground() {
try {
listeningSocket = new ServerSocket(port);
System.out.println("Waiting for connection");
connection = listeningSocket.accept();
connected = true;
System.out.println("Connected");
Scanner in = new Scanner(connection.getInputStream());
out = new PrintWriter(connection.getOutputStream(), true);
publish("Connected");
while (true) {
publish(in.nextLine());
}
} catch (IOException e) {
clientMessage = "Connection Lost";
try {
connection.close();
System.out.println("Closed");
} catch (IOException e1) {
e1.printStackTrace();
connected = false;
}
}
return null;
}
I see your server port is 8900 and your client port is 8900 too. I am not sure if it matters if the server and client are running on the same machine...
I have a little problem with my Client-Server Application. When I want to connect more than 1 Client and send smth, or I make logout in my Client and try to connect one more time I got Exception:
"java.io.StreamCorruptedException: invalid type code: 04"
What's the problem? Thank's for help.
Server Code:
class ClientCommunication implements Runnable {
private Socket incoming;
public ClientCommunication(Socket clientSocket) {
incoming = clientSocket;
}
public void run() {
try {
synchronized (this) {
serverObjectOutput = new ObjectOutputStream(
incoming.getOutputStream());
serverObjectInput = new ObjectInputStream(
incoming.getInputStream());
}
} catch (IOException e) {
e.printStackTrace();
}
int operation = -1;
synchronized(this) {
while (true) {
try{
if(serverObjectInput.available() > 0){
operation = serverObjectInput.readInt();
switch(operation) {
case 1:
Employee employee = (Employee) serverObjectInput.readObject();
//CHECK LOGGING DATA
// SEND RESULT = 1 OR RESULT = -1
break;
}
}
} catch(IOException | ClassNotFoundException | SQLException ex)
{
ex.printStackTrace();
}
}
}
}
}
class ServerStart implements Runnable {
private int portNumber;
public ServerStart(int portNumber) {
this.portNumber = portNumber;
}
public void run() {
try {
conn = getConnection();
stat = conn.createStatement();
} catch (SQLException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
serverSocket = new ServerSocket(portNumber);
} catch (IOException e) {
e.printStackTrace();
}
try {
while (true) {
Socket incoming = serverSocket.accept();
Runnable r = new ClientCommunication(incoming);
Thread t = new Thread(r);
t.start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
Client Function:
public void actionPerformed(ActionEvent e) {
if (isConnected == false) {
String ServerIP = ip.getText().trim();
int ServerPort = Integer
.parseInt(port.getText().trim());
try {
ClientSocket = new Socket(ServerIP, ServerPort);
clientObjectInput = new ObjectInputStream(
ClientSocket.getInputStream());
clientObjectOutput = new ObjectOutputStream(
ClientSocket.getOutputStream());
isConnected = true;
} catch (IOException ex) {
ex.printStackTrace();
}
synchronized (this) {
try {
ClientLoginFrame login = new ClientLoginFrame();
Employee employee = login.getEmployee();
clientObjectOutput.writeInt(1);
clientObjectOutput.flush();
clientObjectOutput.writeObject(employee);
int result = clientObjectInput.readInt();
if(result == 1)
{
// DO SMTH
}
else {
isConnected = false;
ClientSocket.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
});
I suspect your problem is that you are sharing the singletons serverInputStream and serverOutputStream between connections. This isn't a problem until you have more than one at which point using the same stream in multiple threads at once corrupts the stream (or makes reading it invalid)
I built a simple chat application using nio channels. I am very much new to networking as well as threads. This application is for communicating with server (Server / Client chat application).
My problem is that multiple clients are not supported by the server.
How do I solve this problem?
What's the bug in my code?
public class Clientcore extends Thread
{
SelectionKey selkey=null;
Selector sckt_manager=null;
public void coreClient()
{
System.out.println("please enter the text");
BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in));
SocketChannel sc = null;
try
{ sc = SocketChannel.open();
sc.configureBlocking(false);
sc.connect(new InetSocketAddress(8888));
int i=0;
while (!sc.finishConnect())
{
}
for(int ii=0;ii>-22;ii++)
{
System.out.println("Enter the text");
String HELLO_REQUEST =stdin.readLine().toString();
if(HELLO_REQUEST.equalsIgnoreCase("end"))
{
break;
}
System.out.println("Sending a request to HelloServer");
ByteBuffer buffer = ByteBuffer.wrap(HELLO_REQUEST.getBytes());
sc.write(buffer);
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
if (sc != null)
{
try
{
sc.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
} }
public void run()
{
try
{
coreClient();
}
catch(Exception ej)
{
ej.printStackTrace();
}}}
public class ServerCore extends Thread
{
SelectionKey selkey=null;
Selector sckt_manager=null;
public void run()
{
try
{
coreServer();
}
catch(Exception ej)
{
ej.printStackTrace();
}
}
private void coreServer()
{
try
{
ServerSocketChannel ssc = ServerSocketChannel.open();
try
{
ssc.socket().bind(new InetSocketAddress(8888));
while (true)
{
sckt_manager=SelectorProvider.provider().openSelector();
ssc.configureBlocking(false);
SocketChannel sc = ssc.accept();
register_server(ssc,SelectionKey.OP_ACCEPT);
if (sc == null)
{
}
else
{
System.out.println("Received an incoming connection from " + sc.socket().getRemoteSocketAddress());
printRequest(sc);
System.err.println("testing 1");
String HELLO_REPLY = "Sample Display";
ByteBuffer buffer = ByteBuffer.wrap(HELLO_REPLY.getBytes());
System.err.println("testing 2");
sc.write(buffer);
System.err.println("testing 3");
sc.close();
}}}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
if (ssc != null)
{
try
{
ssc.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
catch(Exception E)
{
System.out.println("Ex in servCORE "+E);
}
}
private static void printRequest(SocketChannel sc) throws IOException
{
ReadableByteChannel rbc = Channels.newChannel(sc.socket().getInputStream());
WritableByteChannel wbc = Channels.newChannel(System.out);
ByteBuffer b = ByteBuffer.allocate(1024); // read 1024 bytes
while (rbc.read(b) != -1)
{
b.flip();
while (b.hasRemaining())
{
wbc.write(b);
System.out.println();
}
b.clear();
}
}
public void register_server(ServerSocketChannel ssc,int selectionkey_ops)throws Exception
{
ssc.register(sckt_manager,selectionkey_ops);
}}
public class HelloClient
{
public void coreClientChat()
{
Clientcore t=new Clientcore();
new Thread(t).start();
}
public static void main(String[] args)throws Exception
{
HelloClient cl= new HelloClient();
cl.coreClientChat();
}}
public class HelloServer
{
public void coreServerChat()
{
ServerCore t=new ServerCore();
new Thread(t).start();
}
public static void main(String[] args)
{
HelloServer st= new HelloServer();
st.coreServerChat();
}}
Perfect place for beginers
Hello NIO Server