non blocking client server chat application in java using nio - java

I built a simple chat application using nio channels. I am very much new to networking as well as threads. This application is for communicating with server (Server / Client chat application).
My problem is that multiple clients are not supported by the server.
How do I solve this problem?
What's the bug in my code?
public class Clientcore extends Thread
{
SelectionKey selkey=null;
Selector sckt_manager=null;
public void coreClient()
{
System.out.println("please enter the text");
BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in));
SocketChannel sc = null;
try
{ sc = SocketChannel.open();
sc.configureBlocking(false);
sc.connect(new InetSocketAddress(8888));
int i=0;
while (!sc.finishConnect())
{
}
for(int ii=0;ii>-22;ii++)
{
System.out.println("Enter the text");
String HELLO_REQUEST =stdin.readLine().toString();
if(HELLO_REQUEST.equalsIgnoreCase("end"))
{
break;
}
System.out.println("Sending a request to HelloServer");
ByteBuffer buffer = ByteBuffer.wrap(HELLO_REQUEST.getBytes());
sc.write(buffer);
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
if (sc != null)
{
try
{
sc.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
} }
public void run()
{
try
{
coreClient();
}
catch(Exception ej)
{
ej.printStackTrace();
}}}
public class ServerCore extends Thread
{
SelectionKey selkey=null;
Selector sckt_manager=null;
public void run()
{
try
{
coreServer();
}
catch(Exception ej)
{
ej.printStackTrace();
}
}
private void coreServer()
{
try
{
ServerSocketChannel ssc = ServerSocketChannel.open();
try
{
ssc.socket().bind(new InetSocketAddress(8888));
while (true)
{
sckt_manager=SelectorProvider.provider().openSelector();
ssc.configureBlocking(false);
SocketChannel sc = ssc.accept();
register_server(ssc,SelectionKey.OP_ACCEPT);
if (sc == null)
{
}
else
{
System.out.println("Received an incoming connection from " + sc.socket().getRemoteSocketAddress());
printRequest(sc);
System.err.println("testing 1");
String HELLO_REPLY = "Sample Display";
ByteBuffer buffer = ByteBuffer.wrap(HELLO_REPLY.getBytes());
System.err.println("testing 2");
sc.write(buffer);
System.err.println("testing 3");
sc.close();
}}}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
if (ssc != null)
{
try
{
ssc.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
catch(Exception E)
{
System.out.println("Ex in servCORE "+E);
}
}
private static void printRequest(SocketChannel sc) throws IOException
{
ReadableByteChannel rbc = Channels.newChannel(sc.socket().getInputStream());
WritableByteChannel wbc = Channels.newChannel(System.out);
ByteBuffer b = ByteBuffer.allocate(1024); // read 1024 bytes
while (rbc.read(b) != -1)
{
b.flip();
while (b.hasRemaining())
{
wbc.write(b);
System.out.println();
}
b.clear();
}
}
public void register_server(ServerSocketChannel ssc,int selectionkey_ops)throws Exception
{
ssc.register(sckt_manager,selectionkey_ops);
}}
public class HelloClient
{
public void coreClientChat()
{
Clientcore t=new Clientcore();
new Thread(t).start();
}
public static void main(String[] args)throws Exception
{
HelloClient cl= new HelloClient();
cl.coreClientChat();
}}
public class HelloServer
{
public void coreServerChat()
{
ServerCore t=new ServerCore();
new Thread(t).start();
}
public static void main(String[] args)
{
HelloServer st= new HelloServer();
st.coreServerChat();
}}

Perfect place for beginers
Hello NIO Server

Related

Send objects via java sockets without ObjectOutputStream

I have a socket communication between clients and a server. I design the server side in order to create a new thread every time a client connects to the server. The problem is that, sometimes, ObjectInputStream throws StreamCorruptedException when I try to read and object.
The involved classes implement serializable, and have correct serialVersionUIDs. Also, I used synchronized to avoid problems of synchronization. I tried to flush the objectOutputStream every time I write and object. The problem persist, so it is possible to send objects via a socket communication without use ObjectOutputStream? Send a byte array directly or something like this?
I let some code in case someone sees something I'm doing wrong.
server side
public class ClientHandler implements Runnable {
public static ArrayList<ClientHandler> clientsHandlers = new ArrayList<>();
private Socket socket;
private Server server;
private Usuario usuario;
private ObjectInputStream objectInputStream;
private ObjectOutputStream objectOutputStream;
public ClientHandler(Socket socket, Server server) {
try {
this.socket = socket;
this.server = server;
objectInputStream = new ObjectInputStream(socket.getInputStream());
objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
clientsHandlers.add(this);
} catch (Exception e) {
// TODO: handle exception
disconnect();
}
}
#Override
public void run() {
// TODO Auto-generated method stub
while (!socket.isClosed() && socket.isConnected()) {
try {
synchronized (objectInputStream) {
Object object = objectInputStream.readObject(); // <---PROBLEM
if (object instanceof AccionOnline) {
switch (((AccionOnline) object).getTipoAccionOnline()) {
case DESCONECTAR:
disconnect();
if (server.numConnection == 0) {
server.closeServerSocket();
} else {
sendObject(object);
}
break;
case INICIARPARTIDA:
case DODECAEDRO:
case SIGUIENTE:
case DADO:
case ITEMDADO:
case RULETA:
case TEST:
case DRAWSTART:
case DRAW:
case DRAWUP:
sendObject(object);
break;
}
}
if (object instanceof Usuario) {
this.usuario = (Usuario) object;
for (ClientHandler clientHandler : clientsHandlers) {
if (!clientHandler.equals(this)) {
this.objectOutputStream.writeObject(clientHandler.usuario);
this.objectOutputStream.flush();
}
}
sendObject(object);
}
}
} catch (Exception e) { // TODO: handle exception closeAll(socket, bufferedReader,
disconnect();
}
}
}
public <T> void sendObject(T object) {
for (ClientHandler clientHandler : clientsHandlers) {
try {
clientHandler.objectOutputStream.writeObject(object);
clientHandler.objectOutputStream.flush();
} catch (Exception e) {
// TODO: handle exception
disconnect();
}
}
}
public void disconnect() {
System.out.println("cerrar conexion");
clientsHandlers.remove(this);
try {
if (objectInputStream != null) {
objectInputStream.close();
}
if (objectOutputStream != null) {
objectOutputStream.close();
}
if (socket != null) {
socket.close();
}
server.numConnection--;
} catch (Exception e) {
// TODO: handle exception
}
}
}
client side
public class Client {
private Socket socket;
private ObjectOutputStream objectOutputStream;
private ObjectInputStream objectInputStream;
private ArrayList<GetObject> listeners = new ArrayList<>();
public Client(Socket socket, GetObject listener) {
listeners.add(listener);
try {
this.socket = socket;
this.objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
this.objectInputStream = new ObjectInputStream(socket.getInputStream());
} catch (Exception e) {
// TODO: handle exception
closeAll();
}
}
public void addListener(GetObject listener) {
listeners.add(listener);
}
public void removeListener(GetObject listener) {
listeners.remove(listener);
}
public <T> void sendObject(T object) {
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
objectOutputStream.writeObject(object);
} catch (Exception e) {
closeAll();
}
}
});
thread.start();
}
public void listenServer() {
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
while (socket.isConnected()) {
try {
Object o = objectInputStream.readObject();
for (GetObject listener : listeners) {
listener.getObject(o);
}
} catch (Exception e) {
// TODO: handle exception
closeAll();
}
}
}
}).start();
}
public void closeAll() {
try {
if (objectInputStream != null) {
objectInputStream.close();
}
if (objectOutputStream != null) {
objectOutputStream.close();
}
if (socket != null) {
socket.close();
}
} catch (Exception e) {
// TODO: handle exception
}
}
}

Communicate between a client computer and a vps server JAVA

i know there is alot of post that ask how to comunicate between client and server ,but in the majority those are generally people using the localhost, I have for project to use a vps and several client computer, unfortunately all the solutions given in the other post does not work, indeed the client does not seem to be able to connect to my vps
there is my client code
public IRCClient() throws IOException {
socket = new Socket(InetAddress.getByAddress(new byte[]{(byte) 185, (byte) 242, (byte) 180,97}), 2406);
messages = new LinkedBlockingQueue<Object>();
server = new ConnectionToServer(socket);
Thread messageHandling = new Thread() {
public void run() {
while (true) {
try {
Object message = messages.take();
parse(message);
System.out.println("Message Received: " + message);
} catch (InterruptedException e) {
}
}
}
};
messageHandling.setDaemon(true);
messageHandling.start();
}
private void parse(Object message) {
String msg = String.valueOf(message);
if (msg.contains("-")) {
if (msg.contains("key")) {
key = msg.split("-")[1];
} else if (msg.contains("name")) {
name = msg.split("-")[1];
} else if (msg.contains("world")) {
world = msg.split("-")[1];
} else if (msg.contains("server")) {
serverName = msg.split("-")[1];
} else if (msg.contains("x")) {
x = Integer.parseInt(msg.split("-")[1]);
} else if (msg.contains("y")) {
y = Integer.parseInt(msg.split("-")[1]);
} else if (msg.contains("z")) {
z = Integer.parseInt(msg.split("-")[1]);
} else if (msg.contains("isEntity")) {
entity = msg.split("-")[1].equalsIgnoreCase("true");
} else if (msg.contains("ticks")) {
lTicks = Integer.parseInt(msg.split("-")[1]);
} else if (msg.contains("end")) {
if (key.equalsIgnoreCase(MultiPingMod.getKey()) && !name.equalsIgnoreCase(Minecraft.getMinecraft().thePlayer.getName())) {
MultiPing m = new MultiPing(name, world, serverName, x, y, z, entity);
MultiPingMod.setTime(lTicks);
m.render = true;
if (MultiPingMod.render.getToRender().containsKey(name)) {
MultiPingMod.render.getToRender().get(name).render = false;
MultiPingMod.render.getToRender().remove(name);
}
MultiPingMod.render.addToRender(m);
}
}
}
}
public void send(Object obj) {
server.write(obj);
}
private class ConnectionToServer {
ObjectInputStream in;
ObjectOutputStream out;
Socket socket;
ConnectionToServer(Socket socket) throws IOException {
this.socket = socket;
in = new ObjectInputStream(socket.getInputStream());
out = new ObjectOutputStream(socket.getOutputStream());
Thread read = new Thread() {
public void run() {
while (true) {
try {
Object obj = in.readObject();
messages.put(obj);
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
};
read.setDaemon(true);
read.start();
}
private void write(Object obj) {
try {
out.writeObject(obj);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
i got this code from somewhere in this forum because after lot of attempt nothing was working
same for the server code here is :
public ServerListener() {
debug("Creating the server");
clientList = new ArrayList<ConnectionToClient>();
messages = new LinkedBlockingQueue<Object>();
debug("Client list is created");
try {
serverSocket = new ServerSocket(2406);
debug("opening the port 2406");
} catch (IOException e) {
e.printStackTrace();
debug(e.getMessage());
}
debug("creating the accept thread");
Thread accept = new Thread() {
public void run() {
debug("thread created");
while (true) {
try {
Socket s = serverSocket.accept();
if(s!=null) {
debug("new client joined");
clientList.add(new ConnectionToClient(s));
debug("new client was accepted ["+ s.getInetAddress() + "/" + s.getPort()+"]");
}
} catch (IOException e) {
e.printStackTrace();
debug(e.getMessage());
}
}
}
};
accept.setDaemon(true);
accept.start();
Thread messageHandling = new Thread() {
public void run() {
while (true) {
try {
Object message = messages.take();
debug("we parse the ping");
parse(message);
System.out.println("Message Received: " + message);
} catch (InterruptedException e) {
}
}
}
};
messageHandling.setDaemon(true);
messageHandling.start();
}
private void parse(Object message) {
String msg = String.valueOf(message);
if(msg.contains("-")) {
if(msg.contains("key")) {
debug("key detected");
key = msg.split("-")[1];
} else if(msg.contains("name")) {
debug("name detected");
name = msg.split("-")[1];
} else if(msg.contains("world")) {
debug("worldname detected");
world = msg.split("-")[1];
} else if(msg.contains("server")) {
debug("servername detected");
server = msg.split("-")[1];
} else if(msg.contains("x")) {
debug("x detected");
x = Integer.parseInt(msg.split("-")[1]);
} else if(msg.contains("y")) {
debug("y detected");
y = Integer.parseInt(msg.split("-")[1]);
} else if(msg.contains("z")) {
debug("z detected");
z = Integer.parseInt(msg.split("-")[1]);
} else if(msg.contains("isEntity")) {
debug("entity detected");
entity = msg.split("-")[1].equalsIgnoreCase("true");
} else if(msg.contains("ticks")) {
debug("ticks detected");
lTicks = Integer.parseInt(msg.split("-")[1]);
} else if(msg.contains("end")) {
debug("we got everything detected");
toSend = new IrcMPING(key, name, world, server, x, y, z, entity, lTicks);
for(String str : toSend.getArgs()) {
sendToAll(str);
}
toSend=null;
}
}
}
public void sendToOne(int index, Object message) throws IndexOutOfBoundsException {
clientList.get(index).write(message);
}
public void sendToAll(Object message) {
for (ConnectionToClient client : clientList) {
debug("sending the ping to " + client.socket.getInetAddress());
client.write(message);
}
}
public void debug(String str) {
System.out.println("SOROS DEBUG [MULTIPING] : " + str) ;
}
private class ConnectionToClient {
ObjectInputStream in;
ObjectOutputStream out;
Socket socket;
ConnectionToClient(Socket socket) throws IOException {
this.socket = socket;
in = new ObjectInputStream(socket.getInputStream());
out = new ObjectOutputStream(socket.getOutputStream());
Thread read = new Thread() {
public void run() {
while (true) {
try {
Object obj = in.readObject();
messages.put(obj);
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
};
read.setDaemon(true); // terminate when main ends
read.start();
}
public void write(Object obj) {
try {
out.writeObject(obj);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
i run the jar from the vps (who is based on debian) using the java jar command , but nothing to do i only get this on the terminal
https://cdn.discordapp.com/attachments/832578338567487497/833752196017029170/unknown.png //link to the image
How can i do to make this work ? there is any other way than socket to make two jar communicate from distant computer/server ? thank you for reading me and thank you if you try to help me

Set server listening a sending messages from (servers/client) to (server/client) separately for each client

Trying to write - distributive simulation framework, where program is represented by an array with moving objects, server send command to move, client answer objects out of array
Goal - server send text message to each connected client separately
- client answer
Problem - can not find a way how to implement server listening and writing to one choosed client
Is there anyone, please, who can help me or get some idea?
private ServerSocket serverSocket;
private ArrayList<BufferedReader> clientBufReaders;
private ArrayList<BufferedWriter> clientBufWriters;
public static void main(String[] args) {
Server server = new Server();
}
public Server() {
try {
this.serverSocket = new ServerSocket(23456);
this.clientBufReaders = new ArrayList<BufferedReader>();
this.clientBufWriters = new ArrayList<BufferedWriter>();
this.clients();
} catch (IOException e) {
e.printStackTrace();
}
}
private void clients() {
Thread acceptThread = new Thread(new Runnable() {
private Scanner in;
public void run() {
while (true) {
try {
Socket clientSocket = serverSocket.accept();
clientBufReaders.add(new BufferedReader(new InputStreamReader(clientSocket.getInputStream())));
clientBufWriters.add(new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream())));
this.in = new Scanner(System.in);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
);
acceptThread.start();
while (true) {
synchronized (clientBufReaders) {
for (BufferedReader in : clientBufReaders) {
try {
if (in.ready()) {
System.out.println(in.readLine());
} else {
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}

java socket multiple clients not receiving messages

i am making a java socket chat program and i made it compatible for multiple connections and when a user joins it doesn't send the message "[user] Joined" to all clients just to the one that connected but i have a thread for each client if anyone can tell me why it is only sending the message to the user that recently joined i would greatly appreciate it. Here is the server code
import java.io.*;
import java.net.*;
import java.util.ArrayList;
public class server {
public ObjectInputStream input;
public ServerSocket server;
public Socket s;
public ObjectOutputStream output;
public ArrayList<Socket> users = new ArrayList<Socket>();
public class Accept implements Runnable {
public void run() {
try {
server = new ServerSocket(55555, 100);
} catch (IOException e) {
e.printStackTrace();
}
while(true) {
try {
s = server.accept();
users.add(s);
new EchoThread(s).start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public class EchoThread extends Thread {
private Socket sock;
public EchoThread(Socket s) throws IOException {
this.sock = s;
output = new ObjectOutputStream(sock.getOutputStream());
}
public void run() {
System.out.println(sock.getInetAddress() + " Connected");
try {
for(Socket s: users) {
output.writeObject(s.getInetAddress() + " Connected");
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
server() throws IOException {
Thread t = new Thread(new Accept());
t.start();
}
public static void main(String[] args) throws IOException {
new server();
}
}
So,
Every time someone connects to the server, u create a new EchoThread.
Each User has his own EchoThread.
Your Server role is to manage all the EchoThreads and Sockets.
output.writeObject(s.getInetAddress() + " Connected");
This only sends a message to ONE user.
Your Server should have a List of Sockets and send messages to every Sockets
public ArrayList<Socket> users = new ArrayList<Socket>();
public ArrayList<ObjectOutputStream> outputs = new ArrayList<ObjectOutputStream>();
public class Accept implements Runnable {
public void run() {
try {
server = new ServerSocket(55555, 100);
} catch (IOException e) {
e.printStackTrace();
}
while(true) {
try {
s = server.accept();
users.add(s);
outputs.add(new ObjectOutputStream(s.getOutputStream()));
for (ObjectOutputStream o: outputs) {
o.writeObject(s.getInetAddress() + " has connected");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

Separating Client class from JFrame [duplicate]

A few days ago i tried to create a server - client or client Server as an experiment to learn about socket using a thread but then someone told me that i should use swingWorker. I did some research how to use and have implemented it in as practice but it still doesn't work. the swingWorker thread doesn't look like it is running even tho i get a connection and have used .excute(). If you guys can help spot where i am doing wrong that will be great. SwingWorker class is in the startSever() and startClient() method.
private void startServer() {
SwingWorker <Void, String> runningServer = new SwingWorker<Void, String>(){
protected Void doInBackground() {
try {
listeningSocket = new ServerSocket(port);
System.out.println("waiting for connection");
connection = listeningSocket.accept();
connected = true;
System.out.println("Connected");
String incomeMessage =null;
while(connected){
inStream = connection.getInputStream();
inDataStream = new DataInputStream(inStream);
if (myMessage !=null){
outStream = connection.getOutputStream();
outDataStream = new DataOutputStream(outStream);
outDataStream.writeUTF(myMessage);
}
if((incomeMessage = inDataStream.readUTF())!=null){
clientMessage = incomeMessage;
publish(clientMessage);
incomeMessage =null;
}
}
} catch (IOException e) {
clientMessage = "Connection Lost";
}
return null;
}
runningServer.execute();
}
Here's a VERY basic example.
Basically, because you program requires asynchronous communications (that is, you need to be able to read from the socket AND write to it at the same time), you need to offload each stream to a separate thread.
The management process of this example is, well, no existent. Realistically, you should have some kind of "connection" manager that would be able to cleanly close the output and input threads so that, for example, when the user types "bye", the output thread would be able to tell the connection manager that the connection should be terminated. It would then tell the input thread to stop reading any new message and terminate...
Client
public class Client {
public static void main(String[] args) {
try {
Socket master = new Socket("localhost", 8900);
new Thread(new InputHandler(master)).start();
new Thread(new OuputHandler(master)).start();
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static class InputHandler implements Runnable {
private Socket socket;
public InputHandler(Socket socket) {
this.socket = socket;
}
#Override
public void run() {
boolean commune = true;
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while (commune) {
String text = reader.readLine();
System.out.println("\n<server> " + text);
if (text.toLowerCase().equals("bye")) {
commune = false;
}
}
} catch (Exception exp) {
exp.printStackTrace();
} finally {
try {
reader.close();
} catch (Exception e) {
}
try {
socket.close();
} catch (Exception e) {
}
}
}
}
public static class OuputHandler implements Runnable {
private Socket socket;
public OuputHandler(Socket socket) {
this.socket = socket;
}
#Override
public void run() {
boolean commune = true;
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
Scanner scanner = new Scanner(System.in);
while (commune) {
System.out.print("> ");
String text = scanner.nextLine();
writer.write(text);
writer.newLine();
writer.flush();
if (text.equalsIgnoreCase("bye")) {
commune = false;
}
}
} catch (Exception exp) {
exp.printStackTrace();
} finally {
try {
writer.close();
} catch (Exception e) {
}
try {
socket.close();
} catch (Exception e) {
}
}
}
}
}
Server
public class Server {
public static void main(String[] args) {
try {
ServerSocket master = new ServerSocket(8900);
Socket socket = master.accept();
new Thread(new InputHandler(socket)).start();
new Thread(new OuputHandler(socket)).start();
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static class InputHandler implements Runnable {
private Socket socket;
public InputHandler(Socket socket) {
this.socket = socket;
}
#Override
public void run() {
boolean commune = true;
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while (commune) {
String text = reader.readLine();
System.out.println("\n<client> " + text);
if (text.toLowerCase().equals("bye")) {
commune = false;
}
}
} catch (Exception exp) {
exp.printStackTrace();
} finally {
try {
reader.close();
} catch (Exception e) {
}
try {
socket.close();
} catch (Exception e) {
}
}
}
}
public static class OuputHandler implements Runnable {
private Socket socket;
public OuputHandler(Socket socket) {
this.socket = socket;
}
#Override
public void run() {
boolean commune = true;
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
Scanner scanner = new Scanner(System.in);
while (commune) {
System.out.print("> ");
String text = scanner.next();
writer.write(text);
writer.newLine();
writer.flush();
if (text.equalsIgnoreCase("bye")) {
commune = false;
}
}
} catch (Exception exp) {
exp.printStackTrace();
} finally {
try {
writer.close();
} catch (Exception e) {
}
try {
socket.close();
} catch (Exception e) {
}
}
}
}
}
Update (whine)
While I have your source code in front of me...
There should very, very, rarely be a need to do textMessage.addKeyListener(this)
Because you are using a JTextField, you should be using a ActionListener instead. There are a a number of important reasons for this, but for you, the main one would be the fact that a "accept" action is Look and Feel dependent. While most systems do use Enter as there "accept" action, is not a guarantee.
Have a look at How to Write a Action Listener for more information
Given the general complexity of what you are trying to do, +1 for a overall good attempt!
Using this example, the following changes work with a single telnet client.
private PrintWriter out;
...
public void keyPressed(KeyEvent e) {
if (e.getKeyChar() == KeyEvent.VK_ENTER) {
myMessage = friendLabel + textMessage.getText();
if (out != null) {
out.println(myMessage);
}
...
}
...
protected Void doInBackground() {
try {
listeningSocket = new ServerSocket(port);
System.out.println("Waiting for connection");
connection = listeningSocket.accept();
connected = true;
System.out.println("Connected");
Scanner in = new Scanner(connection.getInputStream());
out = new PrintWriter(connection.getOutputStream(), true);
publish("Connected");
while (true) {
publish(in.nextLine());
}
} catch (IOException e) {
clientMessage = "Connection Lost";
try {
connection.close();
System.out.println("Closed");
} catch (IOException e1) {
e1.printStackTrace();
connected = false;
}
}
return null;
}
I see your server port is 8900 and your client port is 8900 too. I am not sure if it matters if the server and client are running on the same machine...

Categories