I am trying to write a simple client/server Echo application, my client seems to be sending the input, but the server doesn't seem to pick it up and send it back.
Here's the server:
import java.io.*;
import java.net.*;
public class Server
{
public static void main(String args[]) throws Exception
{
int port = 2000;
ServerSocket serverSocket;
Socket client;
BufferedReader is = null;
BufferedWriter os = null;
serverSocket = new ServerSocket(port);
System.err.println("Server established on port " + port);
client = serverSocket.accept();
System.err.println("Client connected");
is = new BufferedReader(
new InputStreamReader(client.getInputStream()));
os = new BufferedWriter(
new OutputStreamWriter(client.getOutputStream()));
System.err.println("Server established on port " + port);
String message = "";
while((message = is.readLine()) != null)
{
System.err.println("Messaged received " + message);
os.write(message);
}
is.close();
os.close();
serverSocket.close();
}
}
Then, the client looks like this:
import java.io.*;
import java.net.Socket;
public class Client
{
public static void main(String args[]) throws Exception
{
String host = "localhost";
int port = 2000;
Socket socket;
socket = new Socket(host, port);
BufferedReader is = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
BufferedWriter os = new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream()));
System.err.println("Connected to " + host + " on port " + port);
BufferedReader br =
new BufferedReader(new InputStreamReader(System.in));
String input = "";
while((input = br.readLine()) != null)
{
System.out.println("Sending " + input);
os.write(input);
System.out.println("Receiving " + is.read());
}
is.close();
os.close();
socket.close();
}
}
What am I missing, I am sure I overlooking something simple.
In the client, try writing the message with a final newline char:
os.write(input+"\n");
(or call also newLine())
That because the server is reading line-by-line.
Related
I am trying to send a message from publisher file (sending on port 8000) which is received by Server (listening on port 5000 and 8000)and which forwards the message to the subscriber(listening on port 5000). The problem is that, communication between publisher and server is fine, however, I am not able to forward the message to the subscriber because the server is still listening to publisher and toggling to the subscriber port and forwarding the message. Any suggestion is appretiated
Publisher
package serverclient;
import java.net.*;
import java.io.*;
public class Publisher {
public static void main (String [] args) throws IOException{
Socket sock = new Socket("127.0.0.1",8000);
// reading from keyboard (keyRead object)
BufferedReader keyRead = new BufferedReader(new InputStreamReader(System.in));
// sending to client (pwrite object)
OutputStream ostream = sock.getOutputStream();
PrintWriter pwrite = new PrintWriter(ostream, true);
InputStream istream = sock.getInputStream();
BufferedReader receiveRead = new BufferedReader(new InputStreamReader(istream));
System.out.println("Start the chitchat, type and press Enter key");
String receiveMessage,sendMessage;
while(true)
{
sendMessage = keyRead.readLine(); // keyboard reading
pwrite.println(sendMessage); // sending to server
pwrite.flush(); // flush the data
if((receiveMessage = receiveRead.readLine()) != null) //receive from server
{
System.out.println(receiveMessage); // displaying at DOS prompt
}
else{
System.out.print("Null");
}
}
}
}
Subscriber
package serverclient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
public class Subscriber {
public static void main (String [] args) throws IOException{
Socket sock = new Socket("127.0.0.1",5000);
// receiving from server ( receiveRead object)
InputStream istream = sock.getInputStream();
BufferedReader receiveRead = new BufferedReader(new InputStreamReader(istream));
System.out.println("Recive side");
System.out.print("Connection Status: " + sock.isConnected() + " " + sock.getPort());
String receiveMessage, sendMessage;
while(true)
{
System.out.print("Hey man " + receiveRead.readLine() + "\n");
if((receiveMessage = receiveRead.readLine()) != null) //receive from server
{
System.out.println(receiveMessage); // displaying at DOS prompt
break;
}
else{
System.out.print("Null");
}
}
}
}
Server
package serverclient;
import java.io.*;
import java.net.*;
public class Server extends Thread{
private Socket socket;
private int clientNumber;
public Server(Socket socket, int clientNumber){
this.socket = socket;
this.clientNumber = clientNumber;
if(socket.getLocalPort() == 5000)System.out.print("\nSubscriber "+ clientNumber +" is connected to the server");
if(socket.getLocalPort() == 8000)System.out.print("\nPublisher "+ clientNumber +" is connected to the server");
}
#Override
public void run(){
try {
BufferedReader dStream = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
System.out.print("\nSocket Address "+ socket.getLocalPort() + " " + socket.getPort());
while(true){
if ( socket.getInputStream().available() != 0 && socket.getLocalPort() == 8000 ){
synchronized(this){
String clMessage = dStream.readLine();
System.out.println(clMessage);
out.println("Hey the publisher has sent the message : " + clMessage);
}
}else if (socket.getInputStream().available() != 0 && socket.getLocalPort() == 5000 ){
out.println("Hey man I am so good");
}
}
} catch (IOException ex) {
System.out.print("\nError has been handled 1\n");
}finally{
try {
socket.close();
} catch (IOException ex) {
System.out.print("\nError has been handled 2\n");
}
}
}
public static void main(String [] args) throws IOException{
int subNumber = 0;
int pubNumber = 0;
ServerSocket servSockpub = new ServerSocket(8000);
ServerSocket servSocksub = new ServerSocket(5000);
try {
while (true) {
Server servpub = new Server(servSockpub.accept(),++pubNumber);
servpub.start();
System.out.print("\nThe server is running on listen port "+ servSockpub.getLocalPort());
Server servsub = new Server(servSocksub.accept(),++subNumber);
servsub.start();
System.out.print("\nThe server is running on listen port "+ servSocksub.getLocalPort());
}
} finally {
servSockpub.close();
servSocksub.close();
}
}
}
I see nothing wrong with the server ports (no duplicates/collisions).
But you have no code whatsoever that bridges data between the 2 sockets.
Basically, you should have 1 server that receives the 2 sockets and move data across in1-out2.
Careful too, in your code you can only connect a subscriber once the publisher has connected.
Found some similar questions but no answer, so here goes -
Attached code is self contained, compilable and runnable to set up a server on my computer. Socket gets created, and I can do a telnet <ip_address> 9162 or telnet localhost 9162 from my local machine. From a remote host, telnet does not get connected. Any ideas? TIA.
import java.io.*;
import java.net.*;
public class TestServerSocket {
public static void main(String args[]) throws IOException {
final int portNumber = 9162;
System.out.println("Creating server socket on port " + portNumber);
ServerSocket serverSocket = new ServerSocket(portNumber);
while (true) {
Socket socket = serverSocket.accept();
OutputStream os = socket.getOutputStream();
PrintWriter pw = new PrintWriter(os, true);
BufferedReader br = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
while (true) {
pw.print("What's you name? ");
pw.flush();
String str = br.readLine();
if (str.trim().length() == 0)
break;
pw.println("Hello, " + str);
}
pw.close();
socket.close();
}
}
}
I am trying to create a simple TCP server and client. I want the client to be able to send multiple messages by only opening the socket once. I have looked at similar questions here, here, and here but they haven't been much use.
My code is a follows:
SampleServerTCP.java
public class SampleServerTCP {
private static final int DEFAULT_PORT_NUMBER = 39277;
public static void main(String[] args) throws IOException {
ServerSocket defaultSocket = new ServerSocket(DEFAULT_PORT_NUMBER);
System.out.println("Listening on port: " + DEFAULT_PORT_NUMBER);
while (true){
Socket connectionSocket = defaultSocket.accept();
BufferedReader fromClient= new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
String msg = fromClient.readLine();
System.out.println("Recieved: " + msg);
}
}
}
TCPClientTest.java
public class TCPClientTest {
public static void main(String args[]) throws UnknownHostException, IOException, InterruptedException{
Socket clientSocket = new Socket("localhost", 39277);
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
int c = 0;
while(c<10){
outToServer.writeBytes(c + "\n");
outToServer.flush();
c++;
Thread.sleep(500);
}
clientSocket.close();
}
}
The only output I get is:
Listening on port: 39277
Recieved: 0
Where am I going wrong?
Your problem lies here:
ServerSocket defaultSocket = new ServerSocket(DEFAULT_PORT_NUMBER);
System.out.println("Listening on port: " + DEFAULT_PORT_NUMBER);
while (true){
Socket connectionSocket = defaultSocket.accept();
BufferedReader fromClient= new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
String msg = fromClient.readLine();
System.out.println("Recieved: " + msg);
}
You are opening the socket, reading only one line and then you are waiting for the next socket.
Instead you should do Socket connectionSocket = defaultSocket.accept(); outside your while loop, and read from this socket in your loop, like this:
System.out.println("Listening on port: " + DEFAULT_PORT_NUMBER);
Socket connectionSocket = defaultSocket.accept();
BufferedReader fromClient= new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
String msg = "";
while ((msg = fromClient.readLine()) != null){
System.out.println("Recieved: " + msg);
}
Change your server side code like below
public class SampleServerTCP {
private static final int DEFAULT_PORT_NUMBER = 39277;
public static void main(String[] args) throws IOException {
ServerSocket defaultSocket = new ServerSocket(DEFAULT_PORT_NUMBER);
System.out.println("Listening on port: " + DEFAULT_PORT_NUMBER);
Socket connectionSocket = defaultSocket.accept();
BufferedReader fromClient= new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
String msg = fromClient.readLine();;
while (msg!=null){
System.out.println("Received: " + msg);
msg = fromClient.readLine();
}
}
}
So this is my first post here, I am currently trying to make a Java client/server chat application using socket programming.
I currently have the server waiting for a client to connect and then passing the client's messages back to the client. So far I have tried different methods to make the server continuously listen to new clients and connect them allowing them to post and view messages with each other.
Can you point me in the right direction and how I should implement this?
SERVER
class TCPServer {
private ServerSocket serverSocket;
private int port;
String newLine = System.getProperty("line.separator");
public TCPServer(int port) {
this.port = port;
}
public void begin() throws IOException {
System.out.println("Starting the server at port: " + port);
serverSocket = new ServerSocket(port);
System.out.println("Waiting for clients... " + newLine);
try {
Socket connectionSocket = serverSocket.accept();
DataOutputStream hello =
new DataOutputStream(connectionSocket.getOutputStream());
hello.writeUTF("You have successfully connected!" + newLine + "please type your username");
//A client has connected to this server. Get client's username
String username = getUserName(connectionSocket);
System.out.println(username + " has connected" + newLine);
//Start chat method
startChat(connectionSocket, username);
} catch (Exception e) {
}
}
public String getUserName(Socket connectionSocket) throws IOException {
String clientUserName;
// ArrayList clients = new ArrayList();
BufferedReader userNameClient =
new BufferedReader(new InputStreamReader(
connectionSocket.getInputStream()));
clientUserName = userNameClient.readLine();
//clients.add(clientUserName);
DataOutputStream greetingFromServer =
new DataOutputStream(connectionSocket.getOutputStream());
//writeUTF Caused incorrect key codes to appear at beginning of String
greetingFromServer.writeBytes("Welcome " + clientUserName + ", please type your message" + newLine);
return clientUserName;
}
public void startChat(Socket connectionSocket, String username) throws IOException {
String clientSentence;
String clientMessageOut;
while (true) {
//Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient =
new BufferedReader(new InputStreamReader(
connectionSocket.getInputStream()));
DataOutputStream outToClient =
new DataOutputStream(connectionSocket.getOutputStream());
//Loops to check if client message is not empty
while ((clientSentence = inFromClient.readLine()) != null) {
outToClient.writeBytes(username + ": " + clientSentence + newLine);
if (clientSentence.equals("close")) {
System.out.println(username + " has left the server");
}
}
}
}
public static void main(String[] args) throws Exception {
int port = 6788;
TCPServer welcomeSocket = new TCPServer(port);
welcomeSocket.begin();
}
}
CLIENT
class TCPClient {
public static void main(String[] args) throws Exception {
String sentence;
String modifiedSentence;
boolean keepConnection = true;
int port = 6788;
Scanner inFromUser = new Scanner(System.in);
Socket clientSocket = new Socket("localhost", 6788);
//System.out.println("You are connented to server"+ '\n'+"Please enter your username: ");
String newLine = System.getProperty("line.separator");
//Recieve greeting message
InputStream messageFromServer = clientSocket.getInputStream();
DataInputStream in =
new DataInputStream(messageFromServer);
System.out.println("FROM SERVER: " + in.readUTF());
DataOutputStream outToServer =
new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer =
new BufferedReader(new InputStreamReader(
clientSocket.getInputStream()));
while ((sentence = inFromUser.nextLine()) != null) {
outToServer.writeBytes(sentence + '\n');
modifiedSentence = inFromServer.readLine();
System.out.println("sentence = " + sentence);
System.out.println(modifiedSentence);
if (sentence.equals("close")) {
System.out.println("You have left the server");
outToServer.writeBytes("close" + newLine);
break;
}
}
clientSocket.close();
}
}
You can use a while(true){} or while((socket = serverSocket.accept()) != null) for the server to loop indefinitely.
To make the server able to connect to multiple clients, you can create a loop where you accept new connections:
while (true) {
try {
Socket connectionSocket = serverSocket.accept();
...
}
...
}
To keep it responsive, you can work with each client in a new thread or maintain a thread pool and submit a task to it for each new connection.
Here is an example (taken from ServerSocketEx) of how you could do it. ServerSocketEx extends ServerSocket, but this is just for ease of use; all of the code following super.accept is relevent to your question.
As others have suggested, you should call accept() in a loop, surrounded by a try { } catch (IOException ...); so that you can shut down if you choose to close the ServerSocket
public Socket accept() throws IOException {
Socket s = super.accept();
if (getSocketRunnerFactory() != null) {
SocketRunner runner = getSocketRunnerFactory().createSocketRunner(s);
if (executor != null) {
Future f =
executor.submit(runner);
if (futures != null) futures.add(f);
}
else {
Thread t = new Thread(runner);
t.start();
}
}
return s;
}
My Issue based on code below:
Run TCPServer.java
then Run TCPClient.java
I expect to have the client print out
Server Said(1): HEY DUDE 1
Server Said(2): HEY DUDE 2
... but it just stays on HEY DUDE 1. What am I doing that is not producing the results I want?
TCPServer.java
import java.io.*;
import java.net.*;
class TCPServer {
public static void main (String args[]) throws Exception{
new TCPServer();
}
TCPServer() throws Exception{
//create welcoming socket at port 6789
ServerSocket welcomeSocket = new ServerSocket(6789);
while (true) {
//block on welcoming socket for contact by a client
Socket connectionSocket = welcomeSocket.accept();
// create thread for client
Connection c = new Connection(connectionSocket);
}
}
class Connection extends Thread{
Socket connectionSocket;
Connection(Socket _connectionSocket){
connectionSocket = _connectionSocket;
this.start();
}
public void run(){
try{
//create input stream attached to socket
BufferedReader inFromClient = new BufferedReader(new InputStreamReader (connectionSocket.getInputStream()));
//create output stream attached to socket
PrintWriter outToClient = new PrintWriter(new OutputStreamWriter(connectionSocket.getOutputStream()));
//read in line from the socket
String clientSentence = inFromClient.readLine();
System.out.println("Client sent: "+clientSentence);
//process
String capitalizedSentence = clientSentence.toUpperCase() + '\n';
//write out line to socket
outToClient.print(capitalizedSentence);
outToClient.flush();
}catch(Exception e){}
}
}
}
TCPClient.java
import java.io.*;
import java.net.*;
class TCPClient {
//String name="";
String host = "localhost";
int port = 6789;
Socket socket = null;
public static void main(String args[]) throws Exception{
TCPClient client = new TCPClient();
client.SendToServer("Hey dude 1");
System.out.println("Server Said(1): "+client.RecieveFromServer());
client.SendToServer("Hey dude 2");
System.out.println("Server Said(2): "+client.RecieveFromServer());
client.close();
}
TCPClient(String _host, int _port) throws Exception{
host = _host;
port = _port;
socket = new Socket(host, port);
}
TCPClient() throws Exception{
socket = new Socket(host, port);
}
void SendToServer(String msg) throws Exception{
//create output stream attached to socket
PrintWriter outToServer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
//send msg to server
outToServer.print(msg + '\n');
outToServer.flush();
}
String RecieveFromServer() throws Exception{
//create input stream attached to socket
BufferedReader inFromServer = new BufferedReader(new InputStreamReader (socket.getInputStream()));
//read line from server
String res = inFromServer.readLine(); // if connection closes on server end, this throws java.net.SocketException
return res;
}
void close() throws IOException{
socket.close();
}
}
Your server thread ends as soon as you process first message. You need to put server code into a loop like this:
String clientSentence;
while ((clientSentence = inFromClient.readLine()) != null) {
System.out.println("Client sent: "+clientSentence);
//process
String capitalizedSentence = clientSentence.toUpperCase() + '\n';
//write out line to socket
outToClient.print(capitalizedSentence);
outToClient.flush();
}