I got basic client-server chat application. Server side seems to work, when I connect with it via telnet, it receives the message and sends it back to all connected clients. I can't achieve the same using my own client tho.
So from the beginning, Server class
public class Server {
private Properties properties;
private ServerSocket serverSocket;
private Set<ClientConnection> clientConnections;
public Server() throws IOException {
clientConnections = new HashSet<>();
serverSocket = new ServerSocket(9999);
while(true){
Socket clientSocket = serverSocket.accept();
ClientConnection clientConnection = new ClientConnection(clientSocket, this);
clientConnections.add(clientConnection);
clientConnection.start();
}
}
public Set<ClientConnection> getClientConnections() {
return clientConnections;
}
}
On every connection is new ClientConnection created that at the beginning, sends "Hello from server" to new client (working if connects via telnet) and then, listens for all incoming messages and broadcast them to all connected clients, again - working if telnet is a client.
public class ClientConnection extends Thread {
private final Socket clientSocket;
private final Server server;
private OutputStream outputStream;
private InputStream inputStream;
public ClientConnection(Socket clientSocket, Server server) {
this.clientSocket = clientSocket;
this.server = server;
}
#Override
public void run(){
try {
handleClient();
} catch (IOException e) {
e.printStackTrace();
}
}
private void handleClient() throws IOException {
outputStream = clientSocket.getOutputStream();
inputStream = clientSocket.getInputStream();
outputStream.write("Hello from server".getBytes());
System.out.println("New client connected");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String incomingMessage;
while((incomingMessage = bufferedReader.readLine()) != null) {
for(ClientConnection connection : server.getClientConnections()) {
connection.getOutputStream().write(incomingMessage.getBytes());
}
System.out.println(incomingMessage);
}
clientSocket.close();
}
public OutputStream getOutputStream() {
return outputStream;
}
}
And then, I got Client application with ServerConnection class
public class ServerConnection{
private Socket socket;
private OutputStream outputStream;
private InputStream inputStream;
private BufferedReader bufferedReader;
private String host;
private int port;
public ServerConnection(String host, int port) {
this.host = host;
this.port = port;
}
public void connect() throws IOException {
socket = new Socket(host, port);
outputStream = socket.getOutputStream();
inputStream = socket.getInputStream();
outputStream.write("Hello from client".getBytes());
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String incommingMessage;
while((incommingMessage = bufferedReader.readLine()) != null) {
System.out.println(incommingMessage);
}
}
}
And it actually is registered by the server side (prints "New client connected"), but it isn't receiving "Hello from client" and the client isn't receiving any messages from the server.
Please try to send new lines at the end of your message from client, i.e.: outputStream.write("Hello from client\r\n\".getBytes());, as you are using bufferedReader.readLine() in your sever code. So BufferedReader is waiting for line end and nothing is happening.
I will not write the code for you, as you have what you need. But here is a flow, that took me a while myself to fully understand, which should help you out.
Server:
Start -> Accept connection -> Read InStream -> Write OutStream (FLUSH THE TOILET OF DATA) -> Loop
Client:
Start -> Connect -> Write OutStream (FLUSH THE TOILET OF DATA) -> Read InStream -> Close Connection
Related
i have an ISO8583 message to send between a client and a server (through sockets). What i did is declare socket and serverSockets classes, start server and accept connections, then create channel both on server and client to apply receive and send methods.
What i got is i cannot print the iso8583 message i send. here is the complete code :
The server's side code :
public class SocketServer {
private ServerSocket serverSocket;
private Socket clientSocket;
private PrintWriter out;
private BufferedReader in;
public void start(int port) throws IOException, ISOException {
serverSocket = new ServerSocket(port);
clientSocket = serverSocket.accept();
ISOChannel channel = new ASCIIChannel (
"localhost", 5000, new ISO87APackager() );
channel.connect();
ISOMsg r = channel.receive ();
System.out.println("isoMsg result "+r.getMTI());
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String data = in.readLine();
System.out.println("Inside Server Socket: " + data);
out.println("Data from server: " + data);
}
public void stop() throws IOException {
in.close();
out.close();
clientSocket.close();
serverSocket.close();
}
public static void main(String[] args) throws IOException, ISOException {
SocketServer server = new SocketServer();
server.start(5000);
System.out.println("Server start...");
}
}
and the client's code :
public class Client
{
public Client(String address, int port) throws ISOException
{
// establish a connection
try
{
Socket socket = new Socket(address, port);
System.out.println("Connected");
ISOChannel channel = new ASCIIChannel (
"localhost", 5000, new ISO87APackager() );
channel.connect();
ISOMsg r=new ISOMsg();
r.setMTI("0200");
channel.send(r);
InputStream in2= socket.getInputStream();
OutputStream out2=socket.getOutputStream();
String line = "";
try
{
in2.close();
out2.close();
socket.close();
}
catch(IOException i)
{
i.printStackTrace();
}
}catch(IOException e){
e.printStackTrace();
}
}
public static void main(String args[]) throws ISOException
{
Client client = new Client("localhost", 5000);
}
}
I am developing a proxy server based on java. For simple http request, proxy server is working. But for HTTPS Connection, connection gets timed out. Here are the steps I did. I first read one line from input stream and created a socket connecting Server. After that I gave 200 Status to client. After that I asynchronously read and write between Client Socket and Server socket. But currently this isn't working and connection gets timedout and I couldn't debug the problem.
public class ProxyServer extends Thread {
private String host;
private int port;
private ServerSocket serverSocket;
private InputStream proxyToClientIP;
private OutputStream proxyToClientOP;
private InputStream proxyToServerIP;
private OutputStream proxyToServerOP;
private Socket socket;
private Socket socketFromProxyServer;
ProxyServer(ServerSocket serverSocket, Socket socket) {
this.serverSocket = serverSocket;
this.socket = socket;
this.start();
}
public void run() {
processInputRequest();
}
public void processInputRequest() {
try {
proxyToClientIP = socket.getInputStream();
proxyToClientOP = socket.getOutputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(proxyToClientIP));
String hostDetails = reader.readLine();
System.out.println(hostDetails);
boolean isConnect = false;
//Need to parse request and find req type as GET or CONNECT
//As of now we assume it to be Connect request
if (!isConnect) {
processGetRequest();
} else {
processConnectRequest();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
public void processConnectRequest() {
//Need to get host name from request. Currently Hardcoded for developing purpose
host = "harish-4072";
port = 8383;
try {
socketFromProxyServer = new Socket(host, port);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(proxyToClientOP));
writer.write("HTTP/1.1 200 Connection established\r\n" + "\r\n");
writer.flush();
proxyToServerOP = socketFromProxyServer.getOutputStream();
proxyToServerIP = socketFromProxyServer.getInputStream();
proxyRequest();
} catch (IOException ex) {
System.out.println(ex);
}
}
public void proxyRequest() {
try {
new Thread() {
#Override
public void run() {
try {
byte[] read = new byte[1024];
int in;
System.out.println("Reading");
while ((in = proxyToClientIP.read(read)) != -1) {
proxyToServerOP.write(read, 0, in);
proxyToServerOP.flush();
}
} catch (SocketException e) {
System.out.println(e);
} catch (IOException ex) {
}
}
}.start();
byte[] reply = new byte[1024];
int out;
System.out.println("Writing");
while ((out = proxyToServerIP.read(reply)) != -1) {
proxyToClientOP.write(reply, 0, out);
proxyToClientOP.flush();
}
} catch (IOException ex) {
}
public void processGetRequest() {
//
}
}
I first read one line from input stream and created a socket connecting Server. ... After that I asynchronously read and write between Client Socket and Server socket.
The problem is that you are reading only a single line while you would need to read the full HTTP request header from the client, i.e. everything up to the end of the request header (\r\n\r\n).
Because you fail to do so the unread parts of the HTTP request are forwarded to the server. But the server is expecting the start of the TLS handshake and these data confuse the server. This might result in hanging or aborting, depending on the content of the data and one the kind of server.
I'm an amateur in java socket programming. As I say in title, When I using PrintStream for socket output,it works;but it doesn't work if I using simply OutputStream.
I know the the client connected to the server cause' the server got the info of the client.So I think there must be something wrong with I/O stream, not the socket connection.
btw, I even use the flush() method for OutputStream.I think flush() will force to send all bytes, but it seems like it didn't work.
The Client Code:#line 12:
public class Clinet {
public static void main(String[] args) throws UnknownHostException, IOException {
System.out.println("==========Client============");
Socket socket = new Socket("localhost", 8888);// Server's addr and port
socket.setSoTimeout(3000);
InputStream inputStream = socket.getInputStream();
OutputStream outputStream = socket.getOutputStream();
String msgToSent = "Hello TCP";
outputStream.write(msgToSent.getBytes());
outputStream.flush();// FIXME:why flush() didn't work?why msg wasn't sent.
// read from socket input
String receivedMsg = new String(inputStream.readAllBytes());
System.out.println(receivedMsg);
socket.close();
}
}
When I using a filter stream like PrintStream,the msg can be sent to server.
The Server Code: if using PrintStream it will work perfectly with the Client:
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(8888);
while (true) {
Socket client = serverSocket.accept();
new Thread(new ServerHandler(client)).start();
}
}
}
class ServerHandler implements Runnable {
private Socket client;
ServerHandler(Socket client) {
this.client = client;
}
#Override
public void run() {
try {
InetAddress clientAddr = client.getInetAddress();
int clientPort = client.getPort();
System.out.println("client connected # " + clientAddr + ":" + clientPort);
InputStream inputStream = client.getInputStream();
OutputStream outputStream = client.getOutputStream();
while (true) {
String msg = new String(inputStream.readAllBytes());// FIXME: Why Server didn't receive Client's msg?
System.out.print("/" + clientAddr + "#" + clientPort + " : ");
System.out.println(msg);
String reply = "I received " + msg.length() + " words.";// return how many words the server got.
outputStream.write(reply.getBytes());
outputStream.flush();// flush to ensure send all msg,but seems doesn't work
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
So I have a client:
public class TalkClient extends Thread
{
private int port;
private String host;
DocCntl theDocCntl;
public TalkClient(String host, int port) throws IOException
{
this.host = host;
this.port = port;
theDocCntl = new DocCntl(this);
}
public void run()
{
try
{
System.out.println("Seeking connection...");
Socket socket = new Socket(host, port);
DataInputStream in = new DataInputStream(socket.getInputStream());
BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
}catch(IOException e)
{
e.printStackTrace();
}
}
public static void main(String [] args)
{
int port = 5050;
try
{
Thread t = new TalkClient("127.0.0.1", port);
t.start();
}catch(IOException e)
{
e.printStackTrace();
}
}
public void pushToServer(){
String theData = this.theDocCntl.theDoc.docTA.getText();
}
}
And I have a server:
public class TalkServer extends Thread
{
private ServerSocket serverSocket;
public static DocCntl theCntl;
public TalkServer(int port) throws IOException
{
serverSocket = new ServerSocket(port);
}
public void run()
{
try
{
System.out.println("Listening for connections...");
Socket client = serverSocket.accept();
DataInputStream in = new DataInputStream(client.getInputStream());
BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
DataOutputStream out = new DataOutputStream(client.getOutputStream());
}catch(IOException e)
{
e.printStackTrace();
}
}
public static void main(String [] args)
{
int port = 5050;
try
{
Thread t = new TalkServer(port);
t.start();
}catch(IOException e)
{
e.printStackTrace();
}
}
}
In the client, I have a method called pushToServer, which I want to take the String data from a textArea on the client, and then push that to all the other connected clients. But I'm not sure how to handle sending the message to each individual connected client through the sockets. I've given it some thought, and I think I need to do 3 things:
1) Create and maintain a list of connected clients(threads). In the server class itself? Or in another class?
2) On the server, have some means of 'catching' the String data from one client, and then pushing it to all the other clients. This is why(I think) I need the list of clients. If I can figure out how to catch this(maybe through the input stream?) and then iterate through the list of clients to their text areas.
3) On the client side, I need to be able to catch the string from the server.
Any help on these 3 things would be greatly appreciated.
I have a client and a server. The client binds a socket on a specific port, the server sends back a new port to the client and the client should bind a new socket on the new port number.
From the main server thread, I start a thread that sends a message to the client once the server is ready and is listening to the new port, so that the client can attempt to connect to the new port. The pipe from the child thread is not sending the message to the client.
So both client and server just freeze, it seems like a deadlock, but im not sure. This line of code in the client: System.out.println("FROM SERVER: " + inMsg_rport); is not executing.
Server Code:
class server
{
public static void main(String argv[]) throws Exception
{
String newPort;
ServerSocket serverSocket = null;
Socket clientSocket = null;
try
{
serverSocket = new ServerSocket(5555);
clientSocket = serverSocket.accept();
DataOutputStream serverOut =
new DataOutputStream(clientSocket.getOutputStream());
int r_port = 5556;
Thread appThread = new Thread(new serverApp(serverOut, r_port));
appThread.start();
}
catch(IOException e)
{
System.out.println(e);
}
}
static class serverApp implements Runnable
{
DataOutputStream serverOut;
int nPort;
public serverApp(DataOutputStream servO, int r_port)
{
this.serverOut = servO;
this.nPort = r_port;
}
#Override
public void run()
{
ServerSocket serverSocket = null;
Socket clientSocket = null;
try
{
serverSocket = new ServerSocket(nPort);
serverOut.writeBytes(sr_port);
clientSocket = serverSocket.accept();
}
catch(IOException e)
{
System.out.println(e);
}
}
}
}
Client code:
class client {
public static void main(String argv[]) throws Exception
{
String serverIp = argv[0];
String msg = argv[2];
int port = Integer.parseInt(argv[1]);
Socket clientSocket = new Socket(InetAddress.getByName(serverIp), port);
BufferedReader clientIn =
new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));
String inMsg_rport = clientIn.readLine();
System.out.println("FROM SERVER: " + inMsg_rport);
int r_port = Integer.parseInt(inMsg_rport);
clientSocket.close();
System.out.println("Closed connection");
Socket new_clientSocket = new Socket(InetAddress.getByName(serverIp), r_port);
}
}
readLine() in your client is a blocking call, waiting for an end-of-line character
http://docs.oracle.com/javase/6/docs/api/java/io/BufferedReader.html#readLine()
You aren't sending an end of line character. You're using a DataOutputStream in your server and sending raw bytes.
Don't use a DataOutputStream in your server; I don't think that's really what you're looking for. Just send the port number as text with an end of line character and be done with it.