I have one client file clientRPC.java and server file serverRPC.java. Both communicate using TCP protocol and use objectinput and output stream to transfer data.
my client file:
public class clientRPC {
public static void main(String args[]) {
Socket s = null;
try {
int serverPort = 8888;
s = new Socket("localhost", serverPort);// server name is local host
//initializing input and output streams object and referencing them to get input and output
ObjectInputStream in = null;
ObjectOutputStream out = null;
out = new ObjectOutputStream(s.getOutputStream());
in = new ObjectInputStream(s.getInputStream());
MathsTutor mt = new MathsTutor();
out.writeObject(mt);
out.flush();
System.out.println("Welcome to Maths Tutor Service. The available maths exercises are:\n"
+ "Addition: Enter 'A' or 'a'\n"
+ "Subtraction: Enter 'S' or 's'\n"
+ "Multiplication: Enter 'M' or 'm'\n"
+ "Division: Enter 'D' or 'd'\n"
+ "Enter 'Q' or 'q' to quit");
//System.out.println();
MathsTutor mt1 = (MathsTutor) in.readObject();
String response = in.readUTF();
System.out.println(response);
} catch (UnknownHostException e) {
System.out.println("Socket:" + e.getMessage());
} catch (EOFException e) {
System.out.println("EOF:" + e.getMessage());
} catch (IOException e) {
System.out.println("readline:" + e.getMessage());
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
} finally {
if (s != null) {
try {
s.close();
} catch (IOException e) {
System.out.println("close:" + e.getMessage());
}
}
}
}
}
and my server file :
public class serverRPC extends Thread {
String request;
String response;
public static void main(String args[]) {
try {
int serverPort = 8888;
ServerSocket listen_socket = new ServerSocket(serverPort);
while (true) {
Socket clientSocket = listen_socket.accept();
Connection c = new Connection(clientSocket);
}
} catch (IOException e) {
System.out.println("Listen socket:" + e.getMessage());
}
public serverRPC(String s) {
request = s;
}
}
class Connection extends Thread {
ObjectInputStream in;
ObjectOutputStream out;
Socket clientSocket;
public Connection(Socket aClientSocket) {
try {
clientSocket = aClientSocket;
in = new ObjectInputStream(clientSocket.getInputStream());
out = new ObjectOutputStream(clientSocket.getOutputStream());
this.start();
} catch (IOException e) {
System.out.println("Connection:" + e.getMessage());
}
}
public void run() {
try {
MathsTutor mt = (MathsTutor) in.readObject();
InetAddress ip = clientSocket.getInetAddress();
System.out.println("The Received Message from Client at address:/" + ip.getHostAddress());
System.out.println("====================================");
MathsTutor mt1 = new MathsTutor();
out.writeObject(mt1);
while(true) {
// Read from input
String command = in.readUTF();
System.out.println(command);
}
//System.out.println();
} catch (EOFException e) {
System.out.println("EOF:" + e.getMessage());
} catch (IOException e) {
System.out.println("readline:" + e.getMessage());
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
} finally {
try {
clientSocket.close();
} catch (IOException e) {/*close failed*/
}
}
}
}
The problem is when I run server and then client on cmd, the client side displays the welcome msg and puts cursor on another line for user input but, I can't type anything, the cursor just blinks... I know this might be simple but it has taken already 3 hours for me and I'm stuck in the same thing.
The cursor marked with red keeps blinking but doesn't let me type anything.
You're writing an object with writeObject() and trying to read it with readUTF(). Illogical.
objects written with writeObject() must be read with readObject().
strings written with writeUTF() must be read with readUTF().
primitives written with writeXXX() must be read with readXXX(), for most values of X.
Related
#FXML
private TextArea textarea;
#FXML
private ImageView imagev;
#Override
public void initialize(URL url, ResourceBundle resourceBundle) {
Serverth Server = new Serverth();
Server.start();
}
class Serverth extends Thread {
#Override
public void run() {
try {
final int NUM_THREAD = 99;
ServerSocket socket = new ServerSocket(8078);
ExecutorService exec = Executors.newFixedThreadPool(NUM_THREAD);
System.out.println("SERVER SOCKET CREATED");
while (!isInterrupted()) {
Socket in = socket.accept();
Runnable r = new ThreadedHandler(in);
exec.execute(r);
}
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
class ThreadedHandler implements Runnable {
private Socket incoming;
public ThreadedHandler(Socket in) {
incoming = in;
}
public void run() {
try {
try {
ObjectInputStream is=new ObjectInputStream(incoming.getInputStream());
while(true) {
if (is.available() > 0) {
String line = is.readUTF();
textarea.appendText("\n" + "[" + new java.util.Date() + "] : " + line);
if (line.contains("inviato")) {
Object obj = is.readObject();
Email ema = (Email) obj;
try {
SimpleDateFormat formatter = new SimpleDateFormat("dd-M-yyyy-hh-mm-ss");
FileOutputStream fileOut = new FileOutputStream("src/Server/" + ((Email) obj).getDestinat() + "/" + formatter.format(((Email) obj).getData()) + ".txt");
ObjectOutputStream objectOut = new ObjectOutputStream(fileOut);
objectOut.writeObject(ema);
objectOut.flush();
objectOut.close();
System.out.println("The Object was succesfully written to a file");
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
} catch(IOException ex) {
ex.printStackTrace();
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
try {
incoming.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
Inside the run method (in Serveth class), I create a server socket and call exec.execute method.
Inside the run method (in ThreadedHandler class), the server is waiting for messages from the client (in this specific case, it creates a new .txt file but it is not important).
Everything works but causes excessive use of the CPU and lag!!!
InputSteam.available method returns a value instantly, telling you no bytes are available to be read, so this code runs a very "hot" spin loop:
while(true) {
if (is.available() > 0) {
...
}
}
The available method is rarely useful and often gives confusing results (see for example inputstream.available() is 0 always). I would suggest you get rid of the if statement altogether:
while(true) {
String line = is.readUTF();
textarea.appendText("\n" + "[" + new java.util.Date() + "] : " + line);
...
}
There's no way for this your code to exit the loop normally. You may want to add a mechanism for the client to disconnect from the server.
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.
public class NewClass {
ServerSocket myServerSocket;
boolean ServerOn = true;
public NewClass() {
try {
myServerSocket = new ServerSocket(8888);
} catch (IOException ioe) {
System.out.println("Could not create server socket on port 8888. Quitting.");
System.exit(-1);
}
while (ServerOn) {
try {
Socket clientSocket = myServerSocket.accept();
ClientServiceThread cliThread = new ClientServiceThread(clientSocket);
cliThread.start();
} catch (IOException ioe) {
System.out.println("Exception found on accept. Ignoring. Stack Trace :");
ioe.printStackTrace();
}
}
try {
myServerSocket.close();
System.out.println("Server Stopped");
} catch (Exception ioe) {
System.out.println("Error Found stopping server socket");
System.exit(-1);
}
}
public static void main(String[] args) {
new NewClass();
}
class ClientServiceThread extends Thread {
Socket myClientSocket;
boolean m_bRunThread = true;
public ClientServiceThread() {
super();
}
ClientServiceThread(Socket s) {
myClientSocket = s;
}
public void run() {
BufferedReader in = null;
PrintWriter out = null;
System.out.println(
"Accepted Client Address - " + myClientSocket.getInetAddress().getHostName());
try {
in = new BufferedReader(new InputStreamReader(myClientSocket.getInputStream()));
out = new PrintWriter(new OutputStreamWriter(myClientSocket.getOutputStream()));
while (m_bRunThread) {
String clientCommand = in.readLine();
if (clientCommand != null) {
System.out.println("Client Says :" + clientCommand);
}
if (!ServerOn) {
System.out.print("Server has already stopped");
out.println("Server has already stopped");
out.flush();
m_bRunThread = false;
}
if (clientCommand.equalsIgnoreCase("quit")) {
m_bRunThread = false;
System.out.print("Stopping client thread for client : ");
} else if (clientCommand.equalsIgnoreCase("end")) {
m_bRunThread = false;
System.out.print("Stopping client thread for client : ");
ServerOn = false;
} else {
out.println("Server Says : " + clientCommand);
out.flush();
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
in.close();
out.close();
myClientSocket.close();
System.out.println("...Stopped");
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
}
Client Code
public class Client {
public static void main(String[] args) throws IOException {
Socket s = new Socket(InetAddress.getLocalHost(), 8888);
PrintWriter out =new PrintWriter(s.getOutputStream(), true);
out.print("KKKKKKKKKKKKK \r\n");
out.flush();
out.close();
}
The purpose of the above code is to create server socket and client socket to pass data between server and client.When the client sends the data to server .server grab the message and print it on the screen but with following exception.The pop up from the String clientCommand = in.readLine(); line which appeared on server code.
java.net.SocketException: Connection reset
Your code is invalid. Your server code relies on the client implementing the protocol correctly, which this client doesn't. Bad habit. Defensive coding is required. If clientCommand == null you must exit this read loop and close the socket. Your present code will attempt to write to the closed connection, which produces exactly this exception ... later.
I have a server that accept more then one Client. Every Client is stored inside an ArrayList of Sockets. If a Client, for some reason, disconnects from my server, this should understand which client has been disconnected, close the client and delete it from the List.
Reading other question here I have understood that the only way to understand which client is disconnected is this: try to send data through all socket connected and the first one which throws Exception has to be closed.
The problem is that if the client is a simple Java-Application it works perfectly. But when the Client is an Android-Application, the data is sent through the (supposed) disconnected Socket. In this way my Server's algorithm doesn't throw Exceptions and it keeps sending data to all Sockets Causing a disaster. The code of clients (java and android) is Exactly the same but the results are different:
Server Code:
List<Socket> sList = new ArrayList<>();
Socket s;
int i = 0;
int whichSocket;
try
{
ServerSocket ss = new ServerSocket(7000);
while (true)
{
System.out.println("Server is Listening");
s = ss.accept();
sList.add(s);
System.out.println("Server Accepted Client --- " +s.toString());
Thread t2 = new Thread(new Runnable() {
public void run() {
try
{
DataInputStream dis = new DataInputStream(s.getInputStream());
while (true)
{
// For every message received from one client, it iterate through list sending that dat to ALL CLIENTS in the list of Socket
String test = dis.readUTF();
System.out.println("Message Sent By -- " + s.toString());
System.out.println(test);
while(i < sList.size()){
DataOutputStream dos = new DataOutputStream(sList.get(i).getOutputStream());
dos.writeUTF(test);
System.out.println("Messaggio Sent To -- " + sList.get(i).toString());
dos.flush();
++i;
}
i=0;
}
} catch (IOException e)
{
System.out.println("First Exception");
e.printStackTrace();
} finally
{
try
{
// An exception has been thrown. This means that one client is disconnected.Which One? Let's send data to all Clients in the list.
whichSocket = -1;
for(Socket temp : sList)
{
System.out.println("PENEEEE inviato a -- " + temp.toString());
whichSocket ++;
DataOutputStream dosser = new DataOutputStream(temp.getOutputStream());
dosser.write(1);
System.out.println("Message Sent To -- " + temp.toString());
dosser.flush();
}
}
catch (IOException e)
{
System.out.println("Second Exception");
e.printStackTrace();
}finally
{
try
{
sList.get(whichSocket).close();
System.out.println("Socket Closed --- " + sList.get(whichSocket).toString());
sList.remove(whichSocket);
} catch (IOException e) {
System.out.println("Third Exception");
e.printStackTrace();
}
}
}
}
});
t2.start();
}
} catch (IOException e) {
System.out.println("General Exception");
e.printStackTrace();
}
Client Code:
while(flag) {
if(!isConnected) {
try {
s = new Socket("192.168.1.69", 7000);
isConnected = true;
DataInputStream dis = new DataInputStream(s.getInputStream());
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
while (flag) {
String result = dis.readUTF();
Log.d("InputStreammmm", result);
}
} catch (IOException e) {
Log.d("THIS IS", "THE EXCEPTIONN");
e.printStackTrace();
} finally {
isConnected = false;
}
}
}
I am writing a single p2p file sharing program that will accept connections and also serve as server itself.
Its in process but Line: 60
Socket sock1= tcpSocket.accept();
throws a Null pointer Exception and i don't know whats wrong. Tried everything.
import java.net.*;
import java.io.*;
public class echoer implements Runnable {
int i,backlog;
public Socket tcpClient= null;
public ServerSocket tcpSocket= null;
public echoer(int tcpPort, int udpPort, int backlog) {
try {
this.tcpSocket = new ServerSocket(tcpPort,backlog);
System.out.println("Server connected to "+ InetAddress.getLocalHost() + "on TCP port " + tcpPort + "and UDP port " + udpPort );
this.backlog= backlog;
listening();
}
catch (SocketTimeoutException s) {
System.out.println("timeout");
}
catch (IOException ioe) {
System.out.println("could not listen on port 10009");
System.exit(-1);
}
}
public echoer () {
}
void listening(){
try {
//i++;
tcpSocket.getInetAddress();
System.out.println();
//Thread t1= new Thread((Runnable) new AcceptInput());
//t1.start();
//tcpSocket.accept();
//System.out.println("Connection accepted");
//messaging();
Thread t2 = new Thread((Runnable) new echoer());
t2.start();
}
catch (Exception e) {
System.out.println("Cannot accept connection");
}
}
public void Client(String addr, int port) throws IOException
{
System.out.println("address= "+ addr+ "port= "+ port);
tcpClient = new Socket(addr,port);
}
/*void messaging () {
System.out.println("Starting Thread");
Thread t = new Thread((Runnable) new echoer());
t.start();
}*/
public void run() {
while (true) {
try {
//System.out.println("Listening on "+ InetAddress.getLocalHost().getHostAddress() + "on TCP port " + tcpSocket.getLocalSocketAddress());
Socket sock1= tcpSocket.accept();
//Client(InetAddress.getLocalHost().getHostAddress(),tcpSocket.getLocalPort());
System.out.println("Connection accepted");
ObjectOutputStream out= new ObjectOutputStream(sock1.getOutputStream());
//Now start the messaging thread nad pass this sock1 to tcpClient
/*String line;
System.out.println("Write a message");
DataInputStream din= new DataInputStream(tcpClient.getInputStream());
line= din.readUTF();
if (line == null) {
din.close();
tcpClient.close();
}
System.out.println("Recvd message:" + line);*/
if (sock1 != null) {
tcpSocket.close();
}
}
catch (IOException o) {
System.out.println("Read Failed");
}
}
}
/*catch (IOException i) {
System.out.println("Last statement");
}
}*/
public static void main(String[] args) {
new echoer(Integer.parseInt(args[0]),Integer.parseInt(args[1]),5);
}
}
class AcceptInput implements Runnable {
String token;
public void run () {
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
try {
token= br.readLine();
if (token== "connect" ) {
System.out.print("Enter IP address: ");
BufferedReader ip= new BufferedReader(new InputStreamReader(System.in));
//accept ip and port
// pass ip and port to tcpclient socket to initiate a connection
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Here's the current problem, you call new Thread((Runnable) new echoer()) and this starts your thread.
However this calls the empty default constructor for echoer which currently has no actual code in it!
So even though you construct the sockets once, after you do that you just create a new instance of echoer with all new sockets and call run() on that
This means that all the sockets in run are null because they were never set and therefore through a NullPointerException when you try to use them.