Sockets - Server getting stuck on in.readLine() - Java - 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.

Related

socket programming transfer data from server to server

i have a client_1 , centerlized_server and server_1
the client send request to a centerlized_server
and centerlized_server transfer the request to the server_1
the problem is how i transfer the request from centerlized_serve to server_1??
I appreciate your help
...
Client1 code
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class Client1 {
private Socket server;
private ObjectOutputStream out;
private ObjectInputStream in;
public Client1() {
try
{
server = new Socket("localhost", 5050);
out = new ObjectOutputStream(server.getOutputStream());
in = new ObjectInputStream(server.getInputStream());
while (true)
{
Scanner s = new Scanner(System.in);
System.out.println("press 2 to date or 1 for time:");
Message msg = new Message();
msg.Type = s.nextInt();
out.writeObject(msg);
msg = (Message) in.readObject();
System.out.println(msg.message);
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
public static void main(String[] args) {
new Client1();
}
}
CernterlizedServer code
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.Date;
public class CentralizedServer extends Thread {
private Socket client;
private ObjectOutputStream out;
private ObjectInputStream in;
public CentralizedServer(Socket current_socket)
{
try
{
client = current_socket;
out = new ObjectOutputStream(client.getOutputStream());
in = new ObjectInputStream(client.getInputStream());
}
catch (Exception ex) {
ex.printStackTrace();
}
}
#Override
public void run()
{
try
{
while (true)
{
Message msg = (Message) in.readObject();
if (msg.Type == 1)
{
OnTimeRequst();
}
else if (msg.Type == 2)
{
OnDateRequst();
}
}
}
catch (Exception ex)
{
try
{
out.close();
in.close();
client.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
private void OnTimeRequst() throws IOException
{
Date d = new Date();
Message msg = new Message();
msg.message = d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
out.writeObject(msg);
}
private void OnDateRequst() throws IOException
{
Date d = new Date();
Message msg = new Message();
msg.message = d.toString() + "";
out.writeObject(msg);
}
}
Server code
import java.net.ServerSocket;
import java.util.ArrayList;
public class Server {
ServerSocket server;
ArrayList<CentralizedServer> list = new ArrayList<>();
public Server()
{
try
{
server = new ServerSocket(5050);
while (true)
{
CentralizedServerthr = new CentralizedServer(server.accept());
list.add(thr);
thr.start();
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
public static void main(String... args) {
new Server();
}
}
You can design this one of two ways.
Option 1: Redirect. The centralized server sends back a response to the client to "redirect" him to server1. (ala http 30x response). Then the client just makes a separate connection to server1 and resends the request.
Option 2: Proxy. Upon receiving the request from the client, the centralized server makes a connection to server1 and sends the request on behalf of the client. When the centralized server receives the response from server1, it just forwards the response to the client.
The redirect method is simpler, but not always possible if "server1" is meant to be protected from direct client access or only accessible from other servers.
The proxy method is a bit harder, but allows for different designs.

Server not getting data from client - 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.

Java Socket Server won't process second client

I've got a client and server coded in Java, once the server has received one message from the client, the server stops receiving all new messages. No errors are thrown when the client tries to sent more messages. I can't seem to find out why it doesn't allow or receive new connections! Please help.
public class Server implements Runnable {
#Override
public void run() {
ServerSocket echoServer = null;
String line;
DataInputStream is;
PrintStream os;
Socket clientSocket = null;
boolean Listening = true;
int sPort = 9999;
// Try to open a server socket on port 9999
try {
echoServer = new ServerSocket(sPort);
}
catch (IOException e) {
System.out.println(e);
}
// Create a socket object from the ServerSocket to listen and accept
// connections.
// Open input and output streams
while (Listening){
try {
clientSocket = echoServer.accept();
is = new DataInputStream(clientSocket.getInputStream());
//os = new PrintStream(clientSocket.getOutputStream());
// As long as we receive data, echo that data back to the client.
while (true) {
line = is.readLine();
if(line != null){
//os.println(line);
log(Level.SEVERE, "New connection to server {0}", line);
}
}
} catch (IOException ex) {
Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
while (true)
{
line = is.readLine();
if(line != null){
//os.println(line);
log(Level.SEVERE, "New connection to server {0}", line);
}
}
after accepting a connection it is entering into this infinite loop.due to this loop it will never accept new connection.
to solve this issues, start new thread each time when new client comes, pass socket connection of the client and read data from that client.
I see two issues as below:
while (true) {
line = is.readLine();
if(line != null){
//os.println(line);
log(Level.SEVERE, "New connection to server {0}", line);
}
Here you need to break after reading the content from the Socket irrespective of whether you read in different thread or same.
You need to declare boolean Listening to volatile else the server wont stop.
while (true) {
line = is.readLine();
if(line != null){
//os.println(line);
log(Level.SEVERE, "New connection to server {0}", line);
}
}
the code will block new request, so the second request will not be accepted.
I make an example accounding to your code. Hope it help to you.
The Server Class will only be userd to accept socket connection and create a new thread to process it.
import java.io.DataInputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.io.Writer;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Server implements Runnable {
#Override
public void run() {
ServerSocket echoServer = null;
boolean listening = true;
Socket clientSocket = null;
int sPort = 9999;
// Try to open a server socket on port 9999
try {
echoServer = new ServerSocket(sPort);
} catch (IOException e) {
System.out.println(e);
}
// Create a socket object from the ServerSocket to listen and accept
// connections.
// Open input and output streams
while (listening) {
try {
clientSocket = echoServer.accept();
System.out.println("receive new connection");
new ProcessClientThread(clientSocket).start();
} catch (IOException ex) {
Logger.getLogger(Server.class.getName()).log(Level.SEVERE,
null, ex);
}
}
}
}
The ProcessClientThread Class extends Thread Class and defined a constructor with a Socket type parameter. Override run method of it. The run method get input stream from socket and print it out. When it accept 0, it will close the scoket connection. Its code like this
import java.io.DataInputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.Socket;
public class ProcessClientThread extends Thread {
Socket socket = null;
public ProcessClientThread(Socket socket) {
this.socket = socket;
}
#Override
public void run() {
DataInputStream is;
String line;
boolean flag = true;
try {
is = new DataInputStream(socket.getInputStream());
while (flag) {
line = is.readLine();
if (Integer.valueOf(line) != 0) {
// os.println(line);
// Logger.getLogger(Level.SEVERE,
// "New connection to server {0}", line);
System.out.println(line);
} else {
Writer w = new OutputStreamWriter(socket.getOutputStream());
w.write(0);
w.flush();
flag = false;
socket.close();
System.out.println("close a connection");
}
}
} catch(Exception e) {
}
}
}
There is a StartUp Class which used to start up the server thread.
public class StartUp {
public static void main(String[] args) {
new Thread(new Server()).start();
}
}
Run the below Client Class to test the Server.
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.net.Socket;
public class Client {
public static void main(String[] args) throws Exception {
Socket client = new Socket("localhost", 9999);
OutputStreamWriter writer = new OutputStreamWriter(client.getOutputStream());
Reader reader = new InputStreamReader(System.in);
Reader serverReader = new InputStreamReader(client.getInputStream());
boolean flag = true;
while(flag) {
int readContent = reader.read();
writer.write(readContent);
writer.flush();
if(readContent == 0) {
writer.close();
client.close();
flag = false;
}
}
}
}

I've created a Java server with sockets, just how do print to ALL sockets?

I've been trying this for a while, and I want multiple clients to recieve multiple inputs simultaneously. There is one problem, I want the server to print "Hi" to all clients if one client says 'print2all Hi'.
I know how to process it to print it, just to print to ALL clients is the problem.
Here's what I have so far.
Server
try{
try{
server = new ServerSocket(25565);
} catch (Exception e){
e.printStackTrace();
}
while (isListening){
new SocketThread(server.accept()).start();
}
server.close();
} catch (Exception e){
e.printStackTrace();
}
SocketThread
try {
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String inputLine, outputLine;
Processor kkp = new Processor();
out.println("Hi!");
while ((inputLine = in.readLine()) != null) {
outputLine = kkp.Proccess(inputLine,this.socket);
out.println(outputLine);
}
out.close();
in.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
Client
Processor p = new Processor();
socket = new Socket("localhost",25565);
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String fromServer;
String fromUser;
out.println("print2all Hi")
socket.close();
First you need to keep track of all connected clients:
final List<SocketThread> clients = new ArrayList<>();
while (isListening){
SocketThread client = new SocketThread(server.accept()).start();
clients.add(client);
}
Having such list if one client receives "print2all Hi" it simply iterates over all clients and sends message to each of them. To do this you'll most likely have to expose some method on SocketThread that will access client socket. This means you'll have to change out variable to field.
Alternative approach is to keep a list of client sockets. But this breaks encapsulation badly. Also you might run into nasty IO/thread-safety issues if sockets are exposed directly. Better hide them behind some API (like SocketThread method) and do the synchronization properly inside.
A full implementation of what you are looking.
Server
package tcpserver;
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 java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;
public class TCPServer {
private int serverPort = 25565;
private ServerSocket serverSocket;
private List<ConnectionService> connections = new ArrayList<ConnectionService>();
public TCPServer() {
try {
serverSocket = new ServerSocket(serverPort);
System.out.println("Waiting...");
while (true) {
Socket socket = serverSocket.accept();
System.out.println("Connected: " + socket);
ConnectionService service = new ConnectionService(socket);
service.start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new TCPServer();
}
class ConnectionService extends Thread {
private Socket socket;
private BufferedReader inputReader;
private PrintWriter outputWriter;
//private String username;
public ConnectionService(Socket socket) {
this.socket = socket;
try {
inputReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
outputWriter = new PrintWriter(socket.getOutputStream(), true);
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
#Override
public void run() {
while (true) {
try {
String receivedMessage = inputReader.readLine();
System.out.println(receivedMessage);
StringTokenizer stoken = new StringTokenizer(receivedMessage);
String fargument = stoken.nextToken();
if (fargument.equals("print2all")) {
this.sendToAnyone(stoken.nextToken());
}
} catch (IOException ex) {
Logger.getLogger(TCPServer.class.getName()).log(Level.SEVERE, null, ex);
} catch (NullPointerException e) {
System.out.println(e.getMessage());
} finally {
outputWriter.close();
}
}
}
protected void sendMessage(String message) {
outputWriter.println(message);
}
private void sendToAnyone(String message) {
for (ConnectionService connection : connections) {
connection.sendMessage(message);
}
}
}
}
Client
package tcpclient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
public class tcpClient extends javax.swing.JFrame {
private Socket socket;
private BufferedReader inputReader;
private PrintWriter outputWriter;
public tcpClient() {
connectToServer();
}
private void connectToServer() {
try {
socket = new Socket(InetAddress.getByName("localhost"), 25565);
inputReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
outputWriter = new PrintWriter(socket.getOutputStream(), true);
} catch (IOException e) {
e.printStackTrace();
}
new Thread() {
#Override
public void run() {
receiveData();
}
}.start();
}
private void receiveData() {
try {
while (true) {
System.out.println(inputReader.readLine());
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void sendData(String messageToSend) {
outputWriter.println(messageToSend);
}
public void closeSocket() {
if (socket != null) {
try {
socket.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
tcpClient client = new tcpClient();
client.sendData("print2all Hi");
client.closeSocket();
}
});
}
}

My Server and Client socket program just hangs without printing anything

Why does nothing get printed out to the console?
I have a server socket which starts a new thread for each client. It reads a line from the client outputs it and sends a response of its own. This is printed on the client side. Here's the code:
The client code:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class Client {
public static void main(String[] args) {
PrintWriter out = null;
BufferedReader in = null;
Socket echoSocket=null;
try {
echoSocket = new Socket("localhost", 8999);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
for(int i=0;i<20;i++) {
out.print("Sending to Server"+i);
System.out.println("Received from Server"+in.readLine());
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
try {
in.close();
} finally {
try {
out.close();
} finally {
echoSocket.close();
}
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
}
The server code:
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.concurrent.Callable;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Server {
/**
* #param args
*/
public static void main(String[] args) {
try {
final ServerSocket server = new ServerSocket(8999);
final ExecutorService threadPool = Executors.newFixedThreadPool(2);
while (true) {
try {
final Socket sock = server.accept();
threadPool.submit(new Callable<Void>() {
#Override
public Void call() throws Exception {
BufferedReader br = null;
PrintWriter out = null;
try {
br = new BufferedReader(new InputStreamReader(sock.getInputStream()));
out = new PrintWriter(sock.getOutputStream(), true);
for (int i = 0; i < 20; i++) {
String readLine = br.readLine();
System.out.println(readLine);
out.print(readLine + "response");
}
} finally {
try {
br.close();
} finally {
try {
out.close();
} finally {
sock.close();
}
}
}
return null;
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Well for one, you should probably println instead of print on your writers (in both client and server).

Categories

Resources