Server not getting data from client - JAVA - java

This is my server code:
package ServerSideHammingCodeCheckingAndResponse;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Server
{
private ServerSocket serverSocket;
private int port;
public Server(int port)
{
this.port = port;
}
public void start() throws IOException
{
System.out.println("Server starts at port:" + port);
serverSocket = new ServerSocket(port);
System.out.println("Waiting for client...");
Socket client = serverSocket.accept();
sendMessage(client, "This is Hamming Code Checking.");
boolean checkInput = false;
String input = null;
while (!checkInput)
{
input = getMessage(client);
if(input.length() == 7 && input.matches("[01]+"))
checkInput = true;
else
sendMessage(client, "invalid");
}
sendMessage(client, input);
}
private void sendMessage(Socket client, String message) throws IOException
{
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
writer.write(message);
writer.flush();
writer.close();
}
private String getMessage(Socket client) throws IOException
{
String userInput;
BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
userInput = reader.readLine();
return userInput;
}
public static void main(String[] args)
{
int portNumber = 9987;
try {
Server socketServer = new Server(portNumber);
socketServer.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
This is my client code:
package ClientSideDataTransmitter;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class Client
{
private String hostname;
private int port;
Socket socketClient;
public Client(String hostname, int port)
{
this.hostname = hostname;
this.port = port;
}
public void connect() throws UnknownHostException, IOException
{
System.out.println("Attempting to connect to " + hostname + ":" + port);
socketClient = new Socket(hostname, port);
System.out.println("\nConnection Established.");
}
public void readResponse() throws IOException
{
String userInput;
BufferedReader reader = new BufferedReader(new InputStreamReader(socketClient.getInputStream()));
System.out.print("Response from server: ");
while ((userInput = reader.readLine()) != null) {
System.out.println(userInput);
}
}
public void sendData() throws IOException
{
Scanner sc = new Scanner(System.in);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socketClient.getOutputStream()));
System.out.println("Enter a 7-bits binary as message to server:\n");
String input = sc.nextLine();
writer.write(input);
writer.flush();
}
public static void main(String arg[])
{
Client client = new Client ("localhost", 9987);
try {
client.connect();
client.readResponse();
client.sendData();
client.readResponse();
} catch (UnknownHostException e) {
System.err.println("Host unknown. Cannot establish connection");
} catch (IOException e) {
System.err.println("Cannot establish connection. Server may not be up." + e.getMessage());
}
}
}
I havent finish up the code so please ignore minor mistakes in the code.
When I start Server, then Client, and send an input from Client to Server. Server seems not getting the data from Client since I send back that input from server to client to print it out, it prints nothing.
I think there may be problems in the method getMessage() in the server code but I cant fix it. Please help me fix the code. Many thanks!
Server:
Server starting at port 9987
Waiting for client...
Client:
Attempting to connect to localhost:9987
Connection Established.
Response from server: This is Hamming Code Checking.
Enter a 7-bits binary as message to server:
1234567
Response from server:

On top of Shriram suggestions I advise you to use PrintWriter here to avoid closing connection. It's also somewhat more convenient to use. Here's working example:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
private ServerSocket serverSocket;
private int port;
public Server(int port) {
this.port = port;
}
public void start() throws IOException {
System.out.println("Server starts at port:" + port);
serverSocket = new ServerSocket(port);
System.out.println("Waiting for client...");
Socket client = serverSocket.accept();
sendMessage(client, "This is Hamming Code Checking.");
boolean checkInput = false;
String input = null;
while (!checkInput) {
input = getMessage(client);
if (input.length() == 7 && input.matches("[01]+"))
checkInput = true;
else
sendMessage(client, "invalid");
}
sendMessage(client, input);
}
private void sendMessage(Socket client, String message) throws IOException {
PrintWriter writer = new PrintWriter(client.getOutputStream(), true);
writer.println(message);
}
private String getMessage(Socket client) throws IOException {
String userInput;
BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
userInput = reader.readLine();
return userInput;
}
public static void main(String[] args) {
int portNumber = 9987;
try {
Server socketServer = new Server(portNumber);
socketServer.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Client:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class Client {
private String hostname;
private int port;
Socket socketClient;
public Client(String hostname, int port) {
this.hostname = hostname;
this.port = port;
}
public void connect() throws UnknownHostException, IOException {
System.out.println("Attempting to connect to " + hostname + ":" + port);
socketClient = new Socket(hostname, port);
System.out.println("\nConnection Established.");
}
public void readResponse() throws IOException {
String userInput;
BufferedReader reader = new BufferedReader(new InputStreamReader(socketClient.getInputStream()));
System.out.print("Response from server: ");
userInput = reader.readLine();
System.out.println(userInput);
}
public void sendData() throws IOException {
Scanner sc = new Scanner(System.in);
PrintWriter writer = new PrintWriter(socketClient.getOutputStream(), true);
System.out.println("Enter a 7-bits binary as message to server:\n");
String input = sc.nextLine();
writer.println(input);
}
public static void main(String arg[]) {
Client client = new Client("localhost", 9987);
try {
client.connect();
client.readResponse();
client.sendData();
client.readResponse();
} catch (UnknownHostException e) {
System.err.println("Host unknown. Cannot establish connection");
} catch (IOException e) {
System.err.println("Cannot establish connection. Server may not be up." + e.getMessage());
}
}
}

The problem with your code is writer.close() in sendMessage() will internally close the writer objects. Your server program will be closed and no longer in connection to accept the connections.

You're losing data by creating a new BufferedReader per message. You need to use the same one for the life of the socket. Ditto 'PrintWriter` or whatever you use to send.

Related

Getting java.net.SocketException Connection reset error in socket communication with threads

I'm basically trying to code a socket communication between multiple clients and a server.
I am getting this error java.net.SocketException: Connection reset. I have read some posts regarding this error, but none of the proposed solutions seems to solve my problem.
Here is the code for the Client : Client.java
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.Scanner;
import javafx.scene.web.PromptData;
public class Client {
private Socket socket;
private boolean running;
public Client(Socket socket) {
this.socket = socket;
running = true;
}
public void sendToServer(String message) throws IOException {
DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream());
outputStream.writeUTF(message);
System.out.println("Die Nachricht : \"" + message + "\" wurde zu dem Server geschickt.");
// outputStream.close();
}
public String waitForNewMessage() throws IOException {
DataInputStream inputStream = new DataInputStream(socket.getInputStream());
String message = inputStream.readUTF();
// inputStream.close();
return message;
}
public void stop() throws IOException {
socket.close();
running = false;
}
public boolean isRunning() {
if (running == true) {
return true;
}
return false;
}
public String promptForNewMessage() {
Scanner scanner = new Scanner(System.in);
System.out.println("Geben Sie eine Nachricht ein.");
String message = scanner.nextLine();
scanner.close();
return message;
}
public void processReceivedMessage(String message) {
System.out.println("Hier ist die Antwort des Servers : " + message);
}
public static void main(String[] args) throws IOException {
//Socket clientSocket = new Socket(args[0], Integer.parseInt(args[1]));
Socket clientSocket = new Socket("localhost",9999);
Client client = new Client(clientSocket);
while (true) {
String message = client.promptForNewMessage();
client.sendToServer(message);
String response = client.waitForNewMessage();
client.processReceivedMessage(response);
if(response.contains("\\exit")) {
System.out.println("Die Verbindung wird geschlossen");
client.stop();
break;
}
}
}
}
The code for the server : Server.java
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class Server {
private int port;
private boolean running;
private ServerSocket serverSocket;
private static Server instance;
private Server() throws IOException {
this.port = loadPortFromConfig("config-datei.txt");
this.running = true;
this.serverSocket = new ServerSocket(this.port);
}
public int loadPortFromConfig(String path) throws FileNotFoundException {
File config = new File(path);
Scanner in = new Scanner(config);
if (in.hasNextLine()) {
String line = in.nextLine().split(":")[1];
in.close();
return Integer.parseInt(line);
}
in.close();
return 9999;
}
public static Server getInstance() throws IOException {
if (instance == null) {
instance = new Server();
}
return instance;
}
public static void main(String[] args) throws IOException {
Server server = Server.getInstance();
if (args.length != 0) {
server.port = Integer.parseInt(args[0]);
}
System.out.println("Der Port des Servers ist : " + server.port);
while(true) {
Socket socket = null;
try {
socket = server.serverSocket.accept();
System.out.println("A new client is connected : " + socket);
System.out.println("Assigning a new thread for this client");
Thread t = new Connection(socket);
t.start();
}
catch(IOException e) {
e.printStackTrace();
}
}
}
static class Connection extends Thread {
private Socket clientSocket;
private boolean running;
public Connection(Socket clientSocket) {
this.clientSocket = clientSocket;
this.running = true;
}
#Override
public void run() {
String fromClient = "";
while(true) {
try {
fromClient = waitForMessage();
System.out.println("Der Client hat die Nachricht : \"" + fromClient + "\" geschickt");
if(fromClient.contains("\\exit")) {
System.out.println("Client "+this.clientSocket + "sneds exit...");
System.out.println("Closing connection.");
sendToClient(fromClient);
System.out.println("Connection closed");
running = false;
break;
}
sendToClient(fromClient);
}
catch(IOException e) {
e.printStackTrace();
}
}
}
public String waitForMessage() throws IOException {
DataInputStream inputStream = new DataInputStream(clientSocket.getInputStream());
String message = inputStream.readUTF();
// inputStream.close();
return message;
}
public void sendToClient(String message) throws IOException {
DataOutputStream outputStream = new DataOutputStream(clientSocket.getOutputStream());
outputStream.writeUTF("Die folgende Nachricht : \"" + message + "\" wurde geschickt");
// outputStream.close();
}
}
}
The error occurs in the line fromClient = waitForMessage(); in the try catch block of the server code
This code calls the method waitForMessage() in the line : String message = inputStream.readUTF();
Do you have any recommendations ? thank you
java.net.SocketException: Connection reset
This means the OS has reseted the connection because the process on the other end is no longer running. It looks like your client crashes after processing first reply from the server.
Scanner scanner = new Scanner(System.in);
scanner.close();
Do not close Scanners operating on System.in. This will close System.in and you will not be able to read anything anymore from there.

What should the Client class of this EchoServer class be?

I am trying to write the Client class of this EchoServer so that the server can echo my input. It seems that the EchoServer can only read the client's inputs and print it without echoing it again.
Here's the EchoServer class.
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class EchoServer implements Runnable {
Socket socket;
public EchoServer(Socket socket) {
this.socket = socket;
}
public void run() {
System.out.printf("connection received from %s\n", socket);
try {
PrintWriter pw = new PrintWriter(socket.getOutputStream());
Scanner in = new Scanner(socket.getInputStream());
while (in.hasNextLine()) {
String line = in.nextLine();
System.out.printf("%s says: %s\n", socket, line);
pw.printf("echo: %s\n", line);
pw.flush();
}
pw.close();
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(4343);
System.out.printf("socket open, waiting for connections on %s\n",serverSocket);
while (true) {
Socket socket = serverSocket.accept();
EchoServer server = new EchoServer(socket);
new Thread(server).start();
}
}
}
This is my EchoClient class, it reads the system input and writes it to the socket.
import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class EchoClient {
Socket socket;
private Scanner in;
private PrintWriter out;
public EchoClient(String address, int port) {
try {
socket = new Socket(address, port);
System.out.println("Connected!");
in = new Scanner(System.in);
out = new PrintWriter(socket.getOutputStream());
} catch (UnknownHostException u) {
System.out.println(u);
} catch (IOException e) {
System.out.println(e);
}
String line = "";
while (!line.equals("over")) {
line = in.nextLine();
out.println(line);
}
out.close();
}
public static void main(String[] args) throws IOException {
EchoClient c1 = new EchoClient("127.0.1.1", 4343);
EchoClient c2 = new EchoClient("127.0.1.1", 4343);
}
}
It seems that the Printwriter of EchoServer is not writing the echo statements. I wonder why?

Exampels on a Server-Client-Chat applikation on JAVA [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 8 years ago.
Improve this question
I have been "googeling" around for a long time for examples over Server-client-chat application, but I can't really understand them. Many of them are using a class and creates the GUI from it, and I don't want to copy straight from it. Alot of examples doesn't either really explain how you send messages from a client to the server and then it sends the message out to all the other clients.
I am using NetBeans and I was wondering if there is some good tutourials or examples that can help me with this?
Here comes the multiThreading program :) the server has two classes, and client has one. Hope you Like it!
SERVER MAIN CLASS:
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Main {
public static void main(String[] args) throws IOException {
int MAXCLIENTS = 20;
int port = 4444;
ServerSocket server = null;
Socket clientSocket = null;
// An array of clientsConnected instances
ClientThread[] clientsConnected = new ClientThread[MAXCLIENTS];
try {
server = new ServerSocket(port);
System.out.println("listening on port: " + port);
} catch (IOException e) {// TODO Auto-generated catch block
e.printStackTrace();
}
while (true) {
try {
clientSocket = server.accept();
} catch (IOException e) {
e.printStackTrace();
if (!server.isClosed()){server.close();}
if (!clientSocket.isClosed()){clientSocket.close();}
}
System.out.println("Client connected!");
for (int c = 0; c < clientsConnected.length; c++){
if (clientsConnected[c] == null){
// if it is empty ( null) then start a new Thread, and pass the socket and the object of itself as parameter
(clientsConnected[c] = new ClientThread(clientSocket, clientsConnected)).start();
break; // have to break, else it will start 20 threads when the first client connects :P
}
}
}
}
}
SERVER CLIENT CLASS:
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
public class ClientThread extends Thread{
private ClientThread[] clientsConnected;
private Socket socket = null;
private DataInputStream in = null;
private DataOutputStream out = null;
private String clientName = null;
//Constructor
public ClientThread(Socket socket, ClientThread[] clientsConnected){
this.socket = socket;
this.clientsConnected = clientsConnected;
}
public void run(){
try {
// Streams :)
in = new DataInputStream(socket.getInputStream());
out = new DataOutputStream(socket.getOutputStream());
String message = null;
clientName = in.readUTF();
while (true){
message = in.readUTF();
for (int c = 0; c < clientsConnected.length; c++){
if (clientsConnected[c]!= null && clientsConnected[c].clientName != this.clientName){ //dont send message to your self ;)
clientsConnected[c].sendMessage(message, clientName); // loops through all the list and calls the objects sendMessage method.
}
}
}
} catch (IOException e) {
System.out.println("Client disconnected!");
this.clientsConnected = null;
}
}
// Every instance of this class ( the client ) will have this method.
private void sendMessage(String mess, String name){
try {
out.writeUTF(name + " says: " + mess);
} catch (IOException e) {
e.printStackTrace();
}
}
}
AND FINALLY THE CLIENT:
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.Scanner;
public class Main
{
public static void main(String[] args) throws IOException {
Main m = new Main();
m.connect();
}
public void connect() throws IOException{
//declare a scanner so we can write a message
Scanner keyboard = new Scanner(System.in);
// localhost ip
String ip = "127.0.0.1";
int port = 4444;
Socket socket = null;
System.out.print("Enter your name: ");
String name = keyboard.nextLine();
try {
//connect
socket = new Socket(ip, port);
//initialize streams
DataInputStream in = new DataInputStream(socket.getInputStream());
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
//start a thread which will start listening for messages
new ReceiveMessage(in).start();
// send the name to the server!
out.writeUTF(name);
while (true){
//Write messages :)
String message = keyboard.nextLine();
out.writeUTF(message);
}
}
catch (IOException e){
e.printStackTrace();
if (!socket.isClosed()){socket.close();}
}
}
class ReceiveMessage extends Thread{
DataInputStream in;
ReceiveMessage(DataInputStream in){
this.in = in;
}
public void run(){
String message;
while (true){
try {
message = in.readUTF();
System.out.println(message);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
I ran the server in eclipse, and started two clients from the CMD, looks like this:
Here is a super simple I made just now with some comments of what is going on. The client connects to the server can can type messages which the server will print out. This is not a chat program since the server receives messages, and the client send them. But hopefully you will understand better it better :)
Server:
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Main {
public static DataInputStream in;
public static DataOutputStream out;
public static void main(String[] args) throws IOException {
int port = 4444;
ServerSocket server = null;
Socket clientSocket = null;
try {
//start listening on port
server = new ServerSocket(port);
System.out.println("Listening on port: " + port);
//Accept client
clientSocket = server.accept();
System.out.println("client Connected!");
//initialize streams so we can send message
in = new DataInputStream(clientSocket.getInputStream());
out = new DataOutputStream(clientSocket.getOutputStream());
String message = null;
while (true) {
// as soon as a message is being received, print it out!
message = in.readUTF();
System.out.println(message);
}
}
catch (IOException e){
e.printStackTrace();
if (!server.isClosed()){server.close();}
if (!clientSocket.isClosed()){clientSocket.close();}
}
}
}
Client:
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.Scanner;
public class Main
{
public static void main(String[] args) throws IOException {
//declare a scanner so we can write a message
Scanner keyboard = new Scanner(System.in);
// localhost ip
String ip = "127.0.0.1";
int port = 4444;
Socket socket = null;
try {
//connect
socket = new Socket(ip, port);
//initialize streams
DataInputStream in = new DataInputStream(socket.getInputStream());
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
while (true){
System.out.print("\nMessage to server: ");
//Write a message :)
String message = keyboard.nextLine();
//Send it to the server which will just print it out
out.writeUTF(message);
}
}
catch (IOException e){
e.printStackTrace();
if (!socket.isClosed()){socket.close();}
}
}
}

Sockets - Server getting stuck on in.readLine() - Java

I've recently been playing around with Sockets in Java but I came across a problem. The server get's stuck in the Server readLine(); I have no clue what is going on, if anyone can help that would be great. I know that the problem is not that readLine() only returns when there is a new line character, but I am using println() not just print().
Here is my current code:
Server Class:
package packets.sidedcomputer;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import packets.Packet;
import packets.data.PacketData;
import packets.info.ClientInfo;
import packets.reciever.PacketReciever;
import packets.sender.PacketSender;
import packets.side.Side;
public class Server extends SidedComputer
{
volatile boolean finished = false;
public ServerSocket serverSocket;
public volatile List<ClientInfo> clients = new ArrayList<ClientInfo>();
public void stopServer()
{
finished = true;
}
public Server()
{
try
{
serverSocket = new ServerSocket(10501);
}
catch (IOException e)
{
e.printStackTrace();
}
}
#Override
public void run()
{
try
{
while (!finished)
{
Socket clientSocket = serverSocket.accept();
if(clientSocket != null)
{
ClientInfo clientInfo = new ClientInfo(clientSocket);
this.clients.add(clientInfo);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String dataString = in.readLine();
while(dataString != null && !dataString.equals(""))
{
PacketReciever packetReciever = new PacketReciever();
PacketData packetData = new PacketData();
packetData.decodeInto(dataString);
Packet packet = packetReciever.recievePacket(packetData, packetData.packetID, getSide(), clientSocket.getLocalAddress().getHostAddress().toString(), clientSocket.getLocalPort() + "");
PacketSender packetSender = new PacketSender();
for (ClientInfo client : this.clients)
{
PrintWriter out = new PrintWriter(client.socket.getOutputStream(), true);
packetSender.sendPacketToClient(packet, out);
}
dataString = in.readLine();
}
serverSocket.close();
}
}
}
catch (Exception e)
{
e.printStackTrace();
System.exit(1);
}
}
#Override
public Side getSide()
{
return Side.SERVER;
}
}
My Client Class:
package packets.sidedcomputer;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
import packets.MessagePacket;
import packets.sender.PacketSender;
import packets.side.Side;
public class Client extends SidedComputer
{
volatile boolean finished = false;
volatile String username;
volatile Server server;
public Socket clientSocket;
public ClientReciever reciever;
public Client(Server server, String username) throws UnknownHostException, IOException
{
this.username = username;
this.server = server;
this.reciever = new ClientReciever(this);
}
public void stopClient()
{
finished = true;
}
#Override
public void run()
{
Scanner scanner = new Scanner(System.in);
reciever.start();
while(!finished)
{
try
{
this.clientSocket = new Socket("192.168.1.25", 10501);
String line;
while((line = scanner.nextLine()) != null)
{
PacketSender sender = new PacketSender();
sender.sendPacket(new MessagePacket(line, username), clientSocket.getLocalAddress().getHostAddress().toString(), "" + clientSocket.getPort());
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
scanner.close();
}
#Override
public Side getSide()
{
return Side.CLIENT;
}
}
My packet sender class:
package packets.sender;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import packets.Packet;
import packets.data.PacketData;
public class PacketSender implements IPacketSender
{
#Override
public void sendPacket(Packet packet, String host, String port)
{
if(packet.getDefualtID() == 0)
{
PacketData packetData = new PacketData(packet.getDefualtID());
packet.writeData(packetData);
String data = packetData.encodeIntoString();
sendData(host, port, data);
}
}
protected void sendData(String hostName, String port, String data)
{
try
{
try
(
Socket socket = new Socket(hostName, Integer.parseInt(port));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
)
{
out.println(data);
}
catch (UnknownHostException e)
{
System.err.println("Don't know about host " + hostName);
System.exit(1);
}
catch (IOException e)
{
System.err.println("Couldn't get I/O for the connection to " + hostName);
System.exit(1);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
public void sendPacketToClient(Packet packet, PrintWriter out)
{
PacketData packetData = new PacketData(packet.getDefualtID());
packet.writeData(packetData);
String data = packetData.encodeIntoString();
out.println(data);
}
}
Here's what's happening
From your client:
this.clientSocket = new Socket("192.168.1.25", 10501);
When this line runs, the server will be woken up from the accept line. And block again at readLine()
Meanwhile, your client, goes through your PacketSender. What does your PacketSender do?
Socket socket = new Socket(hostName, Integer.parseInt(port));
This opens a new connection! So your Client is waiting for the server to accept a connection. And the server is waiting for the client to send a message! You arrive at a deadlock.
Here's how to fix it
remove the following line.
this.clientSocket = new Socket("192.168.1.25", 10501);
then pass the host address and port manually into your PacketSender.

error when the client wants to connect to the server

suppose we use the following classes to illustrate a client and a server :
Client
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;
public class Client {
private PrintWriter toServer;
private BufferedReader fromServer;
private Socket socket;
public Client() throws IOException {
socket = new Socket("127.0.0.1", 3000);
}
public void openStreams() throws IOException {
toServer = new PrintWriter(socket.getOutputStream(), true);
fromServer = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
}
public void closeStreams() throws IOException {
fromServer.close();
toServer.close();
socket.close();
}
public void run() throws IOException {
openStreams();
String msg = "";
Scanner scanner = new Scanner(System.in);
toServer.println("Hello from Client.");
while (!"exit".equals(msg)) {
System.out.println(">");
toServer.println("msg");
String tmp = fromServer.readLine();
System.out.println("Server said: " + tmp);
}
closeStreams();
}
}
Server
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class myServer {
private static ServerSocket serverSocket;
private static Socket socket;
private static PrintWriter toClient;
private static BufferedReader fromClient;
public static void run() throws IOException {
System.out.println("Server is waiting for connections...");
while (true) {
openStreams();
processClient();
closeStreams();
}
}
public static void openStreams() throws IOException {
serverSocket = new ServerSocket(3000);
socket = serverSocket.accept();
toClient = new PrintWriter(socket.getOutputStream(), true);
fromClient = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
}
public static void closeStreams() throws IOException {
fromClient.close();
toClient.close();
socket.close();
serverSocket.close();
}
public static void processClient() throws IOException {
System.out.println("Connection established.");
String msg = fromClient.readLine();
toClient.println("Client said " + msg);
}
}
if , we run the server first and then after server is ready, we run the client, we would get the following error:
Error in Client Software caused connection abort: recv failed
what is the problem?
Be careful about your code
while (true){
openStreams();
processClient();
closeStreams();
}
In this case, the socket connection has always been reset. As a result, the Client cannot create the socket connection successfully.
You should let you code be like:
openStreams();
while(someCondition){
processClient();
}
closeStream();
maybe you can try to use older version of java, similar thing happened to me and when i used sdk 1.6 instead of 1.7 everything fixed

Categories

Resources