BufferedWriter.write() does not seem to work - java

I have two Java applications, where an Android client connects to a server on a computer and sends a message using BufferedWriter over websockets.
The client:
try {
toast("Sending...");
Socket sock = new Socket(ip, PORT);
OutputStream os = sock.getOutputStream();
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));
bw.flush();
bw.write("Hello Server!");
toast("Connected!");
} catch (UnknownHostException e) {
toast(e.getMessage());
} catch (IOException e) {
toast(e.getMessage());
}
The server:
public static void main(String[] args) {
ServerSocket server;
ConnectionThread ct;
Socket s;
ExecutorService es = Executors.newSingleThreadExecutor();
try {
System.out.println("Starting server...");
server = new ServerSocket(1337);
s = server.accept();
ct = new ConnectionThread(s);
es.execute(ct);
} catch (IOException ex) {
ex.printStackTrace();
}
}
The ConnectionThread class:
public class ConnectionThread implements Runnable {
private Socket sock;
private InputStream is;
private BufferedReader br;
private boolean online;
public ConnectionThread(Socket s) {
System.out.println("Creating connection thread.");
this.sock = s;
online = true;
}
#Override
public void run() {
String input = "";
try {
System.out.println("Starting to read...");
is = sock.getInputStream();
br = new BufferedReader(new InputStreamReader(is));
while (online) {
input = br.readLine();
if(input != null){
System.out.print("Received message: ");
System.out.println(input);
}
}
br.close();
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
When I run the server, and then the client, the client will show the "Connected!" toast, and the server's output will be:
Starting server...
Creating connection thread.
Starting to read...
So, it seems like the connection is actually being made, but the message does not arrive. Does anybody know why this could be happening?

Your server is expecting a complete line terminated by a newline. Try:
bw.write("Hello Server!");
bw.newLine();

Do it like this...
String s = new String();
while ((br.readLine())!=null) {
s = s+br.readLine();
System.out.print("Received message: ");
System.out.println(input);
}
}
And
bw.println("Hello Server");

I notice that you don't send an endline on your client, so the BufferedReader.readline() will never return, because it cannot match the \n-character. Try it again with
bw.write("Hello Server!\n");
on the client side.

Related

How can a server broadcast a message to other clients?

The program is intended to have multiple clients connect to a single server and the clients are able to send and receive messages among other clients.
For example if Client A says "Hi", Client B and Client C connected to the server would also receive "Hi".
In my current code, the server only receives the messages sent by the clients.
I'm currently looking for a solution to have the server broadcast the message sent by a client (eg. ClientA) to other clients. Any advice would be much appreciated.
This server class handles the connections of multiple clients with the use of threads:
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
class EchoThread extends Thread {
private Socket socket;
//constructor
public EchoThread(Socket clientSocket) {
this.socket = clientSocket;
}
#Override
public void run() {
DataInputStream inp = null;
try {
inp = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
//print whatever client is saying as long as it is not "Over"
String line = "";
while (!line.equals("Over")) {
try {
line = inp.readUTF();
System.out.println(line);
} catch (IOException e) { System.out.println(e); }
}
//closes connection when client terminates the connection
System.out.print("Closing Connection");
socket.close();
} catch (IOException e) { System.out.println(e); }
}
}
public class Server {
private static final int PORT = 5000;
public static void main(String args[]) {
ServerSocket serverSocket = null;
Socket socket = null;
//starts the server
try {
serverSocket = new ServerSocket(PORT);
System.out.println("Server started");
System.out.println("Waiting for a client ...\n");
} catch (IOException e) { System.out.println(e); }
//while loop to accept multiple clients
int count = 1;
while(true) {
try {
socket = serverSocket.accept();
System.out.println("Client " + count + " accepted!");
count++;
} catch (IOException e) { System.out.println(e); }
//starts the server thread
new EchoThread(socket).start();
}
}
}
and this is the client class (I have multiple instances of this code running):
import java.net.*;
import java.io.*;
public class ClientA {
private Socket socket = null;
private DataInputStream input = null;
private DataOutputStream output = null;
public ClientA(String address, int port) {
//establish connection
try {
socket = new Socket(address, port);
System.out.println("Connected");
//takes input from terminal
input = new DataInputStream(System.in);
//sends output to the socket
output = new DataOutputStream(socket.getOutputStream());
} catch (IOException e) { System.out.println(e); }
//string to read message from input
String line = "";
//keep reading until "Over" is input
while (!line.equals("Over")) {
try {
line = input.readLine();
output.writeUTF(line);
} catch (IOException e) { System.out.println(e); }
}
//close the connection
try {
input.close();
output.close();
socket.close();
} catch (IOException e) { System.out.println(e); }
}
public static void main (String args[]) {
ClientA client = new ClientA("127.0.0.1", 5000);
}
}
Do feel free to correct me on my code comments as I'm still not very familiar with socket programming.
You did well. Just add a thread to receive message in ClientA; and store socket clients in Server.
In fact, Server is also a "client" when is send message to client.
I add some code based on your code. It works well, hope it's helpful.
class EchoThread extends Thread {
//*****What I add begin.
private static List<Socket> socketList = new ArrayList<>();
//*****What I add end.
private Socket socket;
//constructor
public EchoThread(Socket clientSocket) {
this.socket = clientSocket;
socketList.add(socket);
}
#Override
public void run() {
DataInputStream inp = null;
try {
inp = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
//print whatever client is saying as long as it is not "Over"
String line = "";
while (!line.equals("Over")) {
try {
line = inp.readUTF();
System.out.println(line);
//*****What I add begin.
sendMessageToClients(line);
//*****What I add end.
} catch (IOException e) { System.out.println(e); break;}
}
//closes connection when client terminates the connection
System.out.print("Closing Connection");
socket.close();
} catch (IOException e) { System.out.println(e); }
}
//*****What I add begin.
private void sendMessageToClients(String line) throws IOException {
for (Socket other : socketList) {
if (other == socket) {
continue;//ignore the sender client.
}
DataOutputStream output = new DataOutputStream(other.getOutputStream());
output.writeUTF(line);
}
}
//*****What I add end.
}
public class ClientA {
private Socket socket = null;
private DataInputStream input = null;
private DataOutputStream output = null;
public ClientA(String address, int port) {
//establish connection
try {
socket = new Socket(address, port);
System.out.println("Connected");
//takes input from terminal
input = new DataInputStream(System.in);
//sends output to the socket
output = new DataOutputStream(socket.getOutputStream());
//*****What I add begin.
//Here create a thread to receive message from server.
DataInputStream inp = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
new Thread(() -> {
while (true) {
String str;
try {
str = inp.readUTF();
System.out.println(str);
} catch (IOException e) {
e.printStackTrace();//error.
break;
}
}
}, "Client Reveiver.").start();
//*****What I add end.
} catch (IOException e) { System.out.println(e); }
//string to read message from input
String line = "";
//keep reading until "Over" is input
while (!line.equals("Over")) {
try {
line = input.readLine();
output.writeUTF(line);
} catch (IOException e) { System.out.println(e); }
}
//close the connection
try {
input.close();
output.close();
socket.close();
} catch (IOException e) { System.out.println(e); }
}
I would have a single server thread which would maintain a register of the clients, possibly in a concurrent collection. Then I would send each message received from a client to all other clients.

why it says that there is no line in the clients InputStream?(socket programming)

I tried to write a simple program that runs a server and then accepts two clients. Then one of them tries to send a string to another client.
but my code doesn't work and I don't know why.
This is my TestClient class:
public class TestClient extends Thread{
int id;
String Name;
Socket client;
boolean isAsk;
public TestClient(int id,String clientName,boolean isAsk) throws IOException {
this.id=id;
this.Name=clientName;
this.isAsk=isAsk;
}
public void connectTheClientToTheLocalHost(ServerSocket server){
try {
client = new Socket("localhost",1111);
server.accept();
} catch (IOException e) {
e.printStackTrace();
}
}
public void readFromTerminal(){
try {
InputStream is=client.getInputStream();
OutputStream os = client.getOutputStream();
PrintWriter pw = new PrintWriter(os);
pw.println("sdklfsdklfk");
pw.flush();
pw.close();
}catch (IOException e){
e.printStackTrace();
}
}
public void closeTheCientSocket(){
try {
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void write(){
try {
Scanner sc = new Scanner(client.getInputStream());
BufferedWriter bw = new BufferedWriter(new FileWriter(new File("file1.txt")));
String st =sc.nextLine();
bw.write(st);
bw.close();
}catch (IOException e){
e.printStackTrace();
}
}
#Override
public void run() {
if(isAsk){
readFromTerminal();
}
else{
write();
}
}
and this is the main function:
public class PCServer {
public static void main(String[] args){
try {
ServerSocket s = new ServerSocket(1111);
TestClient t1=(new TestClient(1,"reza",true));
TestClient t2=(new TestClient(2,"man",false));
t1.connectTheClientToTheLocalHost(s);
t1.start();
Scanner sc = new Scanner(t1.client.getInputStream());
String st=sc.nextLine();
System.out.println(st);
t1.closeTheCientSocket();
t2.connectTheClientToTheLocalHost(s);
PrintWriter pw = new PrintWriter(t2.client.getOutputStream());
pw.println(st);
pw.flush();
t2.start();
t2.closeTheCientSocket();
}catch (Exception e){
e.printStackTrace();
}
}
}
actually this code returns an exception in
String st=sc.nextLine();
in main function and says that there is no line found.
what is the problem?
ServerSocket in java usually used in another way.
If you need point-to-point connection, one host creates a ServerSocket and accepts connections. Examples:
First host example:
try(ServerSocket serverSocket = new ServerSocket(5555);
Socket socket = serverSocket.accept();
// it more convenient to use DataInputStream instead of Scanner I think
DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());
DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());) {
while (!Thread.currentThread().isInterrupted()) {
String msg = dataInputStream.readUTF();
System.out.println("got request: " + msg);
dataOutputStream.writeUTF("1-response");
dataOutputStream.flush();
}
} catch (IOException e) {
e.printStackTrace();
}
Second host example:
try(Socket socket = new Socket("127.0.0.1", 5555);
DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());
DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream())) {
while (!Thread.currentThread().isInterrupted()) {
dataOutputStream.writeUTF("2-request");
dataOutputStream.flush();
String msg = dataInputStream.readUTF();
System.out.println("got response: " + msg);
}
} catch (IOException e) {
e.printStackTrace();
}
If you want one host talk to another over the server (broker), then you need plane java Sockets on hosts and ServerSocket on broker, and broker must transmit messages it received from one host to another. Examples:
Broker (run it in separate thread or process)
try {
List<Socket> sockets = new ArrayList<>();
ServerSocket serverSocket = new ServerSocket(5555);
// accepting connections from 2 clients
for (int i = 0; i < 2; i++) {
Socket socket = serverSocket.accept();
sockets.add(socket);
}
// streams for first host
InputStream hostOneInputStream = sockets.get(0).getInputStream();
DataInputStream hostOneDataInputStream = new DataInputStream(sockets.get(0).getInputStream());
DataOutputStream hostOneDataOutputStream = new DataOutputStream(sockets.get(0).getOutputStream());
// streams for second host
InputStream hostTwoInputStream = sockets.get(1).getInputStream();
DataInputStream hostTwoDataInputStream = new DataInputStream(sockets.get(1).getInputStream());
DataOutputStream hostTwoDataOutputStream = new DataOutputStream(sockets.get(1).getOutputStream());
while (!Thread.currentThread().isInterrupted()) {
if (hostOneInputStream.available() > 0) {
String msg = hostOneDataInputStream.readUTF();
System.out.println("got message from host 1: " + msg);
hostTwoDataOutputStream.writeUTF(msg);
hostTwoDataOutputStream.flush();
System.out.println("message " + msg + " sent to host two");
}
if (hostTwoInputStream.available() > 0) {
String msg = hostTwoDataInputStream.readUTF();
System.out.println("got message from host 2: " + msg);
hostOneDataOutputStream.writeUTF(msg);
hostOneDataOutputStream.flush();
System.out.println("message " + msg + " sent to host one");
}
}
} catch (IOException e) {
e.printStackTrace();
}
First host (run it in separate thread or process)
try(Socket socket = new Socket("127.0.0.1", 5555);
DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());
DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream())) {
while (!Thread.currentThread().isInterrupted()) {
dataOutputStream.writeUTF("1");
dataOutputStream.flush();
String msg = dataInputStream.readUTF();
System.out.println("got msg: " + msg);
TimeUnit.SECONDS.sleep(5);
}
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
Second host (run it in separate thread or process)
try(Socket socket = new Socket("127.0.0.1", 5555);
DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());
DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream())) {
while (!Thread.currentThread().isInterrupted()) {
String msg = dataInputStream.readUTF();
System.out.println("got msg: " + msg);
TimeUnit.SECONDS.sleep(5);
dataOutputStream.writeUTF("2");
dataOutputStream.flush();
}
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}

Java while(true) loop executes only once inside thread

I am trying to implement a simple client-server application in Java.
Here is the code:
Client.java
public class Client implements Runnable {
private String hostName;
private int portNumber;
private String message;
private Socket socket;
private PrintWriter writer;
private BufferedReader reader;
public Client(String hostName, int portNumber, String message) {
this.hostName = hostName;
this.portNumber = portNumber;
this.message = message;
}
public void connect() {
try {
socket = new Socket(hostName, portNumber);
writer = new PrintWriter(socket.getOutputStream(), true);
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
writer.println(message);
} catch (UnknownHostException e) {
System.err.println("Could not resolve the host name '" + hostName + "'.");
} catch (IOException e) {
System.err.println("Could not get the I/O for the connection to '" + hostName + "'.");
}
}
private void listenForMessages() {
while (true) {
try {
System.out.println("In loop!");
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.err.println(e.getMessage());
}
}
}
public void run() {
connect();
listenForMessages();
}
}
Server.java
public class Server implements Runnable {
private int portNumber;
private String message;
private ServerSocket serverSocket;
private Socket clientSocket;
private PrintWriter writer;
private BufferedReader reader;
public Server(int portNumber, String message) {
this.portNumber = portNumber;
this.message = message;
}
private void listen() {
try {
serverSocket = new ServerSocket(portNumber);
} catch (IOException e) {
System.err.println(e.getMessage());
}
while (true) {
try {
clientSocket = serverSocket.accept();
writer = new PrintWriter(clientSocket.getOutputStream(), true);
reader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
writer.println(message);
} catch (IOException e) {
System.err.println(e.getMessage());
break;
}
}
}
public void run() {
listen();
}
}
And this is the main class:
public class Test {
public static void main(String[] args) {
Client client = new Client("localhost", 4444, "Hello from client!");
Server server = new Server(4444, "Hello from server!");
Thread serverThread = new Thread(server);
serverThread.start();
Thread clientThread = new Thread(client);
clientThread.start();
}
}
The logic of the code is simple: both the client and the server are waiting for messages inside a while(true) loop.
The while loop inside the server's listen method executes just fine. However, inside the listenForMessages method, the loop seems to be executed only once. I only see one "In loop" printed on the screen.
Can you figure out what the problem is?
Thank you in advance!
However, inside the listenForMessages method, the loop seems to be
executed only once. I only see one "In loop" printed on the screen.
Actually it is not because the loop is executed only once it is simply because reader.readLine() will make the current thread wait until it receives an entire line and here if you check the code of the Server, it reads first and it reads in an infinite loop as reader.readLine() will only return null at the end of the stream so when the socket will be closed in this case.
If you want to implement some kind of ping-pong between the client and the server, simply read then write on one side and write and read and the other side as next:
Client code:
public void connect() {
try {
socket = new Socket(hostName, portNumber);
writer = new PrintWriter(socket.getOutputStream(), true);
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Could not resolve the host name '" + hostName + "'.");
} catch (IOException e) {
System.err.println(
"Could not get the I/O for the connection to '" + hostName + "'."
);
}
}
private void listenForMessages() {
while (true) {
try {
System.out.println("In loop!");
// Write the message for the server
writer.println(message);
// Read the message from the server
System.out.println(reader.readLine());
} catch (IOException e) {
System.err.println(e.getMessage());
}
}
}
Server code:
while (true) {
try {
clientSocket = serverSocket.accept();
writer = new PrintWriter(clientSocket.getOutputStream(), true);
reader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
while (true) {
// Read the message from the client
System.out.println(reader.readLine());
// Write the message for the client
writer.println(message);
}
} catch (IOException e) {
System.err.println(e.getMessage());
break;
}
}
Output:
In loop!
Hello from client!
Hello from server!
In loop!
Hello from client!
Hello from server!
...

How to connect multiple wifi device to a server

I am developing a web application in which I make use of socket to connect to wifi device. I was successful in connecting as well as communicating with the connected device. Now I want to connect multiple wifi device to my server. Can anyone help me on this, below is my code
public class ScheduleJob extends ServletApp implements Job{
private int port = 1717;
public static String number;
String ReceivedData = "";
public void execute(JobExecutionContext context)throws JobExecutionException {
System.out.println("Starting ... ");
ServerSocket Sersocket = null;
System.out.println("Starting the socket server at port:" +port);
boolean listeningSocket = true;
try {
Sersocket = new ServerSocket(port);
System.out.println("Waiting for clients...");
} catch (IOException e) {
System.err.println("Could not listen on port: 1717");
}
try {
while (listeningSocket) {
Socket scokt = Sersocket.accept();
String MachineAdd = scokt.getInetAddress().toString();
System.out.println("Response-----" +MachineAdd);
try{
InputStream inStream = scokt.getInputStream();
InputStreamReader inReader = new InputStreamReader(inStream);
BufferedReader br = new BufferedReader(inReader);
ReceivedData = br.readLine();
System.out.println("ReceivedData :- "+ReceivedData);
}catch(IOException e){
e.printStackTrace();
}
//Sending the response back to the client.
OutputStream outStream = scokt.getOutputStream();
OutputStreamWriter outWriter = new OutputStreamWriter(outStream);
BufferedWriter bw = new BufferedWriter(outWriter);
bw.write("hello");
bw.flush();
}
Sersocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

BufferedReader from server does not work

In this code I can correctly receive a request using BufferedReader inClient, created on the client socket.
Then I send the request to the server and I see the server gets it.
But then, when I try to read the reply from the server (using BufferedReader inServer on the socket of the server), it always ends in IOException: Impossible read from server.
I am referring to the block ################
Do you know any possible reasons?
import java.io.*;
import java.net.Socket;
import java.net.ServerSocket;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class ProxyMain {
public static void main(String argv[]) {
int proxyPort = 55554;
String proxyAddr = "127.0.0.1";
ServerSocket proxySocket = null;
try {
proxySocket = new ServerSocket(proxyPort, 50, InetAddress.getByName("127.0.0.1"));
}
catch (Exception e) {
System.err.println("Impossible to create socket server!");
System.out.flush();
System.exit(1);
}
System.out.printf("Proxy active on port: %d and on address %s\n", proxyPort, proxySocket.getInetAddress());
System.out.println();
while (true) {
Socket client = null;
Socket sockServ = null;
BufferedReader inClient = null;
PrintWriter outClient = null;
BufferedReader inServer = null;
PrintWriter outServer = null;
String request = new String();
String tmp = new String();
String reply = new String();
String tmpReply = new String();
try {
client = proxySocket.accept();
System.out.println("Connected to: ");
System.out.println(client.getInetAddress().toString());
System.out.printf("On port %d\n", client.getPort());
System.out.println();
inClient = new BufferedReader(new InputStreamReader(client.getInputStream()));
outClient = new PrintWriter(client.getOutputStream(), true);
}
/*catch (IOException e) {
System.err.println("Couldn't get I/O for connection accepted");
System.exit(1);
}*/
catch (Exception e) {
System.out.println("Error occurred!");
System.exit(1);
}
System.out.println("Received request:");
try{
for (int i = 0; i<2; i++) {
tmp = inClient.readLine();
request = request + tmp;
}
inClient.close();
}
catch (IOException ioe) {
System.err.println("Impossible to read mhttp request!");
System.exit(1);
}
System.out.println(request);
System.out.println();
try {
sockServ = new Socket("127.0.0.1", 55555);
outServer = new PrintWriter(sockServ.getOutputStream(), true);
inServer = new BufferedReader(new InputStreamReader(sockServ.getInputStream()));
}
catch (UnknownHostException e) {
System.err.println("Don't know about host: 127.0.0.1:55555");
System.exit(1);
}
catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to: 127.0.0.1:55555");
System.exit(1);
}
outServer.println(request);
outServer.close();
try {
#################################################
while ((tmpReply = inServer.readLine()) != null) {
System.out.println(tmpReply);
reply = reply + tmpReply;
}
inServer.close();
sockServ.close();
}
catch (IOException ioe) {
System.err.println("Impossible to read from server!");
System.exit(1);
}
outClient.println(reply);
outClient.close();
try {
client.close();
}
catch (IOException ioe) {
System.err.printf("Impossible to close connection with %s:%d\n", client.getInetAddress().toString(), client.getPort());
}
}
}
}
UPDATE:
It seems that if I do:
boolean res = inServer.ready();
it always return false.
So Server is not ready to send the reply but this is strange...with my Project in C e Python it worked immediately. Why should java be different?
When you close outServer, you close the underlying socket. if you just want to close the output and keep the input open, you need to use Socket.shutdownOutput(). note, you have the same problem when you close inClient.
This works, maybe you can get some ideas from it...
ChatServer - broadcasts to all connected clients
In one command prompt: java ChartServer
In another: java ChatClient localhost (or the ip address of where the server is running)
And another: java ChatClient localhost (or the ip address of where the server is running)
Start chatting in the client windows.
Server like this...
// xagyg wrote this, but you can copy it
import java.io.*;
import java.net.*;
import java.util.*;
public class ChatServer {
public static List list = new ArrayList();
public static void main(String[] args) throws Exception {
ServerSocket svr = new ServerSocket(4444);
System.out.println("Chat Server started!");
while (true) {
try {
Socket s = svr.accept();
synchronized(list) {
list.add(s);
}
new Handler(s, list).start();
}
catch (IOException e) {
// print out the error, but continue!
System.err.println(e);
}
}
}
}
class Handler extends Thread {
private Socket s;
private String ipaddress;
private List list;
Handler (Socket s, List list) throws Exception {
this.s = s;
ipaddress = s.getInetAddress().toString();
this.list = list;
}
public void run () {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(s.getInputStream()));
String message;
//MyDialog x = (MyDialog)map.get(ipaddress.substring(1));
while ((message = reader.readLine()) != null) {
if (message.equals("quit")) {
synchronized(list) {
list.remove(s);
}
break;
}
synchronized(list) {
for (Object object: list) {
Socket socket = (Socket)object;
if (socket==s) continue;
PrintWriter writer = new PrintWriter(socket.getOutputStream());
writer.println(ipaddress + ": " + message);
writer.flush();
}
}
}
try { reader.close(); } catch (Exception e) {}
}
catch (Exception e) {
System.err.println(e);
}
}
}
Client like this ...
// xagyg wrote this, but you can copy it
import java.util.*;
import java.io.*;
import java.net.*;
public class ChatClient {
public static void main(String[] args) throws Exception {
Socket s = new Socket(args[0], 4444);
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintWriter out = new PrintWriter(s.getOutputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String message;
new SocketReader(in).start();
while ((message = reader.readLine())!=null) {
out.println(message);
out.flush();
if (message.equals("quit")) break;
}
in.close();
out.close();
}
}
class SocketReader extends Thread {
BufferedReader in;
public SocketReader(BufferedReader in) {
this.in = in;
}
public void run() {
String message;
try {
while ((message = in.readLine())!=null) {
System.out.println(message);
}
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
}

Categories