Multithreading echo server - java

Hello it is my first topic here.
I wrote some code to making connection client-server by sockets. As a client I mean opening terminal window and connection to this server by telnet. Application works as a server listening for requests from client on specified port. Every single connection is treat as a new thread. Once the connection is bound the client can send a message and gets an answer back as an echo.
The problem is I want to be informed when the client closes the terminal window (finish thread). I want to know id of this closed thread.
This is full code:
public class MultithreadEchoServer
{
public static void main(String[] args) throws IOException
{
int count=0;
long[] ids = new long[10];
try (ServerSocket ss = new ServerSocket(1234))
{
System.out.println("Listening...");
while(true)
{
count++;
Socket s = ss.accept();
Runnable r = new MyThread(s, count);
Thread t = new Thread(r);
t.start();
ids[count-1] = t.getId();
if(Thread.activeCount() != count+1)
{
count = Thread.activeCount();
System.out.println("Client "+/*??thread's id??*/" left the session. Now connected: "+count);
}
System.out.println("Clients connected: "+count);
System.out.println(ids[count-1]);
}
}
}
}
class MyThread implements Runnable
{
private Socket s;
private int count;
private long id;
InputStream io;
OutputStream os;
private PrintWriter pw;
MyThread(Socket s, int count)
{
this.s = s;
this.count = count;
}
public long getId()
{
id = Thread.currentThread().getId();
return id;
}
#Override
public void run()
{
try
{
io = s.getInputStream();
os = s.getOutputStream();
}
catch (IOException e) {System.err.println(e);}
try (Scanner sc = new Scanner(io))
{
pw = new PrintWriter(os, true);
pw.println("Connected");
while(sc.hasNextLine())
{
String line = sc.nextLine();
System.out.println("Client "+count+": "+line);
pw.println("Echo: "+line);
}
}
}
}

Why you donn't print Thread ID inside Thread execution with a finally statement after your try with resource statement :
try (Scanner sc = new Scanner(io))
{
pw = new PrintWriter(os, true);
pw.println("Connected");
while(sc.hasNextLine())
{
String line = sc.nextLine();
System.out.println("Client "+count+": "+line);
pw.println("Echo: "+line);
}
}
finally {
System.out.println("Client " + this.id + " left the session."");
}
MultithreadEchoServer
public class MultithreadEchoServer
{
public static void main(String[] args) throws IOException
{
int count=0;
long[] ids = new long[10];
try (ServerSocket ss = new ServerSocket(1234))
{
System.out.println("Listening...");
while(true)
{
count++;
Socket s = ss.accept();
Runnable r = new MyThread(s, count);
Thread t = new Thread(r);
t.start();
ids[count-1] = t.getId();
if(Thread.activeCount() != count+1)
{
count = Thread.activeCount();
System.out.println("Now connected: "+count);
}
System.out.println("Clients connected: "+count);
System.out.println(ids[count-1]);
}
}
}
}
MyThread
class MyThread implements Runnable
{
private Socket s;
private int count;
private long id;
InputStream io;
OutputStream os;
private PrintWriter pw;
MyThread(Socket s, int count)
{
this.s = s;
this.count = count;
}
public long getId()
{
id = Thread.currentThread().getId();
return id;
}
#Override
public void run()
{
try
{
io = s.getInputStream();
os = s.getOutputStream();
}
catch (IOException e) {System.err.println(e);}
try (Scanner sc = new Scanner(io))
{
pw = new PrintWriter(os, true);
pw.println("Connected");
while(sc.hasNextLine())
{
String line = sc.nextLine();
System.out.println("Client "+count+": "+line);
pw.println("Echo: "+line);
}
}
finally {
System.out.println("Client " + this.id + " left the session."");
}
}
}

Related

Java application with TCP sockets is using 100% of CPU

The server has to continuously listen for incoming connections and perform some logic on the data received. Every time I run the application, the CPU usage is more than 90%. Earlier I thought that the while loop might be spinning (busy waiting), but the readLine() is supposed to be a blocking call, so I don't think that is the case. Any help is appreciated!
The following is the server code:
public void listen() throws IOException
{
try( ServerSocket serverSocket = new ServerSocket(port);
Socket clientSocket = serverSocket.accept();
DataOutputStream outputStream = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));)
{
String data = null;
while((data = bufferedReader.readLine()) != null)
{
Message message = Message.deserializeMessage(data);
synchronized (PeerNode.requestHistory)
{
if(PeerNode.requestHistory.keySet().contains(message))
{
continue;
}
}
if(message.getType() == 0 && message.getHopCount() < 1) {
continue;
}
switch(message.getType()) {
case 0:
synchronized (PeerNode.sharedRequestBuffer){
PeerNode.sharedRequestBuffer.offer(message);
}
break;
case 1:
synchronized (PeerNode.sharedReplyBuffer) {
PeerNode.sharedReplyBuffer.offer(message);
}
break;
case 2:
synchronized (PeerNode.numberOfItems) {
if(PeerNode.numberOfItems > 0) {
PeerNode.numberOfItems -= 1;
}
outputStream.writeBytes("0" + "\n");
}
break;
}
synchronized (PeerNode.requestHistory) {
PeerNode.requestHistory.put(message, 0);
}
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
Edit: Added deserialize() method
public static Message deserializeMessage(String s)
{
Message m = new Message();
String[] objArray = s.split("#");
String[] list = objArray[2].split(",");
m.setProductName(objArray[0]);
m.setProductId(Integer.parseInt(objArray[1]));
List<Integer> tempList = new ArrayList();
for(int i=0; i<list.length; i++)
{
if(list[i].length() == 0)
continue;
tempList.add(Integer.parseInt(list[i]));
}
m.setMessagePath(tempList);
m.setHopCount(Integer.parseInt(objArray[3]));
m.setType(Integer.parseInt(objArray[4]));
m.setRequestId(Integer.parseInt(objArray[5]));
m.setSourcePeerId(Integer.parseInt(objArray[6]));
m.setDestinationSellerId(Integer.parseInt(objArray[7]));
m.setDestinationSellerLocation(Integer.parseInt(objArray[8]));
return m;
}
Edit 2: Changed deserialize() to use Scanner():
public static Message deserializeMessage(String s)
{
Message m = new Message();
Scanner sc = new Scanner(s);
sc.useDelimiter("#");
m.setProductName(sc.next());
m.setProductId(Integer.parseInt(sc.next()));
List<Integer> tempList = new ArrayList();
Scanner sct = new Scanner(sc.next());
sct.useDelimiter(",");
while(sct.hasNext())
{
tempList.add(Integer.parseInt(sct.next()));
}
m.setMessagePath(tempList);
m.setHopCount(Integer.parseInt(sc.next()));
m.setType(Integer.parseInt(sc.next()));
m.setRequestId(Integer.parseInt(sc.next()));
m.setSourcePeerId(Integer.parseInt(sc.next()));
m.setDestinationSellerId(Integer.parseInt(sc.next()));
m.setDestinationSellerLocation(Integer.parseInt(sc.next()));
return m;
}
Edit: Updated Server Code:
private ExecutorService executor = Executors.newFixedThreadPool(15);
public void listen() throws IOException
{
serverSocket = new ServerSocket(port);
while (!Thread.interrupted()) {
try
{
//Server, Listening........
clientSocket = serverSocket.accept();
ServerExecutor serverExecutor = new ServerExecutor(peerID, clientSocket);
executor.submit(serverExecutor);
}
catch (IOException e)
{
e.printStackTrace();
}
}
serverSocket.close();
}
ServerExecutor class:
public ServerExecutor(int _peerID, Socket _clientSocket)
{
this.peerID = _peerID;
this.clientSocket = _clientSocket;
}
public void run()
{
try( DataOutputStream outputStream = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));)
{
String data = null;
while((data = bufferedReader.readLine()) != null)
{
Message message = Message.deserializeMessage(data);
synchronized (PeerNode.requestHistory)
{
if(PeerNode.requestHistory.keySet().contains(message))
{
continue;
}
}
if(message.getType() == 0 && message.getHopCount() < 1) {
continue;
}
switch(message.getType()) {
case 0:
synchronized (PeerNode.sharedRequestBuffer){
PeerNode.sharedRequestBuffer.offer(message);
}
break;
case 1:
synchronized (PeerNode.sharedReplyBuffer) {
PeerNode.sharedReplyBuffer.offer(message);
}
break;
case 2:
synchronized (PeerNode.numberOfItems) {
if(PeerNode.numberOfItems > 0) {
PeerNode.numberOfItems -= 1;
}
outputStream.writeBytes("0" + "\n");
}
break;
}
synchronized (PeerNode.requestHistory) {
PeerNode.requestHistory.put(message, 0);
}
}
clientSocket.close();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
Updated deserialize():
public static Message deserializeMessage(String s)
{
Message m = new Message();
Scanner sc = new Scanner(s);
sc.useDelimiter("#");
m.setProductName(sc.next());
m.setProductId(sc.nextInt());
List<Integer> tempList = new ArrayList();
Scanner sct = new Scanner(sc.next());
sct.useDelimiter(",");
while(sct.hasNext())
{
tempList.add(sct.nextInt());
}
m.setMessagePath(tempList);
m.setHopCount(sc.nextInt());
m.setType(sc.nextInt());
m.setRequestId(sc.nextInt());
m.setSourcePeerId(sc.nextInt());
m.setDestinationSellerId(sc.nextInt());
m.setDestinationSellerLocation(sc.nextInt());
return m;
}
Are you using different thread for each new client connection and also this kinda code will never occupy such a high % of CPU load. Is there some other functionality that's running in the background as well?
Edit:
Maybe you can try something like this?
while (true)
{
Socket s = null;
ServerSocket serverSocket = new ServerSocket(5555);
try
{
s = ss.accept(); //ss is the server socket object
DataOutputStream out = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader int = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
//create a new Thread for the client
Thread t = new TaskHandler(s, in, out); //run method of Task Handler can have the code you want to execute for each connected client
t.start();
}
catch (Exception e){
s.close();
e.printStackTrace();
}
}
Does this help?

Server doesn't work with more than one connection

I've got a working simple client-server app. The problem is it works fine just with one started client, but not with two or more. It establish connection, but when you try to enter text in first or second, the server breakes. I think that problem may be at the function broadcast() in Server.java.
Server.java
public class Server {
final int PORT = 5000;
private ArrayList<NewClient> al = new ArrayList<NewClient>();
private Scanner in;
private PrintWriter out;
private SimpleDateFormat sdf;
private int uniqueID = 0;
private void go(){
try{
ServerSocket serverSocket = new ServerSocket(PORT);
System.out.println("Waiting for clients...");
while(true) {
Socket s = serverSocket.accept();
NewClient chat = new NewClient(s);
System.out.println("Client number " + chat.getId() + " connected from: " + s.getLocalAddress().getHostName());
al.add(chat);
Thread t = new Thread(chat);
t.start();
}
}catch (Exception e) {
System.out.println("Problem with establishing network connection: ");
e.printStackTrace();
}
}
public static void main(String[] args) {
Server server = new Server();
server.go();
}
class NewClient implements Runnable{
private Socket socket;
private int id;
public NewClient(Socket s) {
this.socket = s;
this.id = ++uniqueID;
}
public int getId() {
return this.id;
}
#Override
public void run() {
try{
in = new Scanner(socket.getInputStream());
out = new PrintWriter(socket.getOutputStream());
sdf = new SimpleDateFormat("HH:mm:ss");
while(true) {
String input = in.nextLine();
System.out.println("Client said: " + input);
broadcast(input);
}
}catch (Exception e) {
e.printStackTrace();
}
}
private void writeMsg(String input) {
String msg = input + " on " + sdf.format(new Date());
out.println("You said: " + msg);
out.flush();
}
private void broadcast(String input) {
for (int i = 0; i < al.size(); i++) {
NewClient t = al.get(i);
t.writeMsg(input);
}
}
}
}
Client.java:
public class Client {
final int PORT = 5000;
final String HOST = "127.0.0.1";
private Scanner stdIn;
private Scanner in;
private PrintWriter out;
private void go() {
setUpNetwork();
}
private void setUpNetwork(){
try{
Socket s = new Socket(HOST, PORT);
System.out.println("You are connected to " + HOST);
NewClient client = new NewClient(s);
Thread t = new Thread(client);
t.start();
} catch (Exception e) {
System.out.println("Problem with connection to server: " + e);
}
}
public static void main(String[] args) {
Client client = new Client();
client.go();
}
class NewClient implements Runnable {
private Socket socket;
public NewClient(Socket s) {
this.socket = s;
}
#Override
public void run() {
try {
stdIn = new Scanner(System.in);
in = new Scanner(socket.getInputStream());
out = new PrintWriter(socket.getOutputStream());
while(true) {
System.out.print("> ");
String input = stdIn.nextLine();
out.println(input);
out.flush();
if(in.hasNext()) {
System.out.println(in.nextLine());
}
}
}catch (Exception e) {
e.printStackTrace();
}
}
}
}
When opens two Client.java and connect it to the server.java everything is ok. But when i try to send some message from this two opened clients server returns these errors:
java.lang.IndexOutOfBoundsException: end
at java.util.regex.Matcher.region(Matcher.java:1038)
at java.util.Scanner.findPatternInBuffer(Scanner.java:1010)
Client said: sds
at java.util.Scanner.findWithinHorizon(Scanner.java:1679)
at java.util.Scanner.nextLine(Scanner.java:1538)
at Server$NewClient.run(Server.java:66)
at java.lang.Thread.run(Thread.java:745)
What's happening is that your code scans the first line from the client ("sds", which is printed to stdout), and then it loops back and immediately tries to scan the next line from the client. Since the client hasn't sent anything more yet, the input stream scanner throws an exception.
The NewClient class is an inner class. All instances of this class are created with the same instance of the outer class. Changing the code will sove the problem:
public NewClient(Socket s) {
this.socket = s;
this.id = ++uniqueID;
try{
in = new Scanner(socket.getInputStream());
out = new PrintWriter(socket.getOutputStream());
sdf = new SimpleDateFormat("HH:mm:ss");
}catch(Exception e) {
System.out.println("Exception while creating input/output streams: " + e);
}
}

my proxy server doesn't work as expected

I developed a simple, multi-threaded proxy server. Note that this program is a proxy for one specific server. Here is my code :
public class Proxy {
int remotePort;
InetAddress remoteHost;
public Proxy(InetAddress remoteHost, int remotePort) {
this.remotePort = remotePort;
this.remoteHost = remoteHost;
}
public void go() {
ExecutorService pool = Executors.newCachedThreadPool();
try (ServerSocket server = new ServerSocket(2015);) {
System.out.println("Proxy is running....!");
while (true) {
Socket socketClient = server.accept();
System.out.println("client connected...!");
Socket socketServer = new Socket(remoteHost, remotePort);
System.out.println("connection established with the server...!");
Worker p1 = new Worker(socketClient, socketServer);
Worker p2 = new Worker(socketServer, socketClient);
pool.execute(p1);
pool.execute(p2);
}
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
class Worker implements Runnable {
Socket from, to;
public Worker(Socket from, Socket to) {
this.from = from;
this.to = to;
}
#Override
public void run() {
System.out.println(Thread.currentThread().getName());
try (BufferedInputStream bis = new BufferedInputStream(from.getInputStream());
BufferedOutputStream bos = new BufferedOutputStream(to.getOutputStream());) {
while (true) {
int octet = bis.read();
if (octet == -1) {
break;
}
bos.write(octet);
}
bos.flush();
from.close();
to.close();
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
}
public static void main(String[] args) {
InetAddress adr = null;
try {
adr = InetAddress.getLocalHost();
} catch (UnknownHostException ex) {
System.out.println(ex.getMessage());
}
new Proxy(adr, 2020).go();
}
}
I would like to test this proxy server with a client and a server. the client sends an array of integers to find the maximum. the server of his turn, returns the maximum of a received array.
the problem is the following: the proxy server is not playing its role. the array is not sent to the server and the client not received the maximum value of its array.
The code of my Server is as follow:
public class ServerTCPMax {
static void display(int[] tab) {
for (int u : tab) {
System.out.print(u + " ");
}
System.out.println();
}
static int searchMax(int[] t) {
int max = t[0];
for (int i = 1; i < t.length; i++) {
if (t[i] > max) {
max = t[i];
}
}
return max;
}
public static void main(String[] args) {
try {
ServerSocket server = new ServerSocket(2020);
System.out.println("server is running .......! ");
while (true) {
try (Socket sclient = server.accept()) {
System.out.println("Proxy connected...!");
ObjectInputStream ois = new ObjectInputStream(sclient.getInputStream());
int[] tab = (int[]) ois.readObject();
display(tab);
int max = searchMax(tab);
try (DataOutputStream dos = new DataOutputStream(sclient.getOutputStream())) {
dos.writeInt(max);
dos.flush();
}
}
}
} catch (IOException | ClassNotFoundException ex) {
System.out.println(ex.getMessage());
}
}
}
The following code represents my client:
public class ClientTCPMax {
public static void main(String[] args) {
int[] A = {3, -7, 9, 22, 0, 7, 11, 2};
try {
try (Socket socket = new Socket("127.0.0.1", 2015)) {
System.out.println("connection established with the Proxy ...!");
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
oos.writeObject(A);
oos.flush();
DataInputStream dis = new DataInputStream(socket.getInputStream());
int max = dis.readInt();
System.out.println(" the max is : " + max);
}
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
}

java.net.SocketException: Connection Reset

I'm trying to write a socket program where a string is sent to the server, reversed and the reversed string is sent back to the client.
Here's my server code:
import java.io.*;
import java.net.*;
class ClientSystem
{
public static void main(String[] args)
{
String hostname = "127.0.0.1";
int port = 1234;
Socket clientsocket = null;
DataOutputStream output =null;
BufferedReader input = null;
try
{
clientsocket = new Socket(hostname,port);
output = new DataOutputStream(clientsocket.getOutputStream());
input = new BufferedReader(new InputStreamReader(clientsocket.getInputStream()));
}
catch(Exception e)
{
System.out.println("Error occured"+e);
}
try
{
while(true)
{
System.out.println("Enter input string ('exit' to terminate connection): ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String inputstring = br.readLine();
output.writeBytes(inputstring+"\n");
//int n = Integer.parseInt(inputstring);
if(inputstring.equals("exit"))
break;
String response = input.readLine();
System.out.println("Reversed string is: "+response);
}
output.close();
input.close();
clientsocket.close();
}
catch(Exception e)
{
System.out.println("Error occured."+e);
}
/*finally
{
output.close();
input.close();
clientsocket.close();
}*/
}
}
Here's my server code:
import java.io.*;
import java.net.*;
public class ServerSystem
{
ServerSocket server = null;
Socket clientsocket = null;
int numOfConnections = 0, port;
public ServerSystem(int port)
{
this.port = port;
}
public static void main(String[] args)
{
int port = 1234;
ServerSystem ss = new ServerSystem(port);
ss.startServer();
}
public void startServer()
{
try
{
server = new ServerSocket(port);
}
catch(Exception e)
{
System.out.println("Error occured."+e);
}
System.out.println("Server has started. Ready to accept connections.");
while(true)
{
try
{
clientsocket = server.accept();
numOfConnections++;
ServerConnection sc = new ServerConnection(clientsocket, numOfConnections, this);
new Thread(sc).start();
}
catch(Exception e)
{
System.out.println("Error occured."+e);
}
}
}
public void stopServer()
{
System.out.println("Terminating connection");
System.exit(0);
}
}
class ServerConnection extends Thread
{
BufferedReader br;
PrintStream ps;
Socket clientsocket;
int id;
ServerSystem ss;
public ServerConnection(Socket clientsocket, int numOfConnections, ServerSystem ss)
{
this.clientsocket = clientsocket;
id = numOfConnections;
this.ss = ss;
System.out.println("Connection "+id+" established with "+clientsocket);
try
{
br = new BufferedReader(new InputStreamReader(clientsocket.getInputStream()));
ps = new PrintStream(clientsocket.getOutputStream());
}
catch(Exception e)
{
System.out.println("Error occured."+e);
}
}
public void run()
{
String line;
try
{
boolean stopserver = false;
while(true)
{
line = br.readLine();
System.out.println("Received string: "+line+" from connection "+id);
long threadID = Thread.currentThread().getId();
System.out.println("Thread ID: "+threadID+" is doing the current task.");
if(line.equals("exit"))
{
stopserver = true;
break;
}
else
{
int len = line.length();
String reversedstring = "";
for (int i=len-1; i>=0; i--)
reversedstring = reversedstring + line.charAt(i);
ps.println(""+reversedstring);
}
}
System.out.println("Connection "+id+" is closed.");
br.close();
ps.close();
clientsocket.close();
if(stopserver)
ss.stopServer();
}
catch(Exception e)
{
System.out.println("Error occured."+e);
}
}
}
I'm trying to open two clients. When I type "exit" in one of the clients (say client1), the server itself is terminating. But I don't want the server to close but just the connection to client1 to close. When I next type a string in client2, I get "java.net.SocketException: Connection Reset" .
How do I get rid of the exception and the connection at server be still open for client2?
It's your code:
while(true){
...
if(line.equals("exit"))
{
stopserver = true;
break;
}
...
}
...
if(stopserver)
ss.stopServer();

Java Server Sockets: My Server Socket only allows client connections running on the same internet connection?

Ok so I have constructed a working example of a client and server which can accept multiple client connections. My problem is is that I cannot connect a client which is not running the same internet connection as the one the server is being hosted on. Is this possible using server sockets?
Here is the code for my server:
import java.io.IOException;
import java.net.*;
public class MultipleSocketServer {
public static Socket connection;
public static String name = "Tyler's Server";
public static int limit = 2;
public static Thread[] clients = new Thread[limit];
public static int current = 0;
public static int port = 25565;
public static String[] connected = new String[limit];
public static ServerSocket socket;
public static void main(String[] args) {
System.out.println("Server starting...");
for(int i = 0; i < limit; i++) {
connected[i] = "";
}
try {
ServerSocket socket = new ServerSocket(port);
while(true) {
Socket connection = socket.accept();
String ip = connection.getRemoteSocketAddress().toString().substring(1, 13);
loop:
for(int i = 0; i < connected.length; i++) {
if(connected[0].equals(ip) || connected[1].equals(ip)) {
break loop;
}else if(!connected[i].equals(ip)) {
connected[i] = ip;
MultiServer_Client client = new MultiServer_Client(connection, i);
Thread run = new Thread(client);
run.start();
break loop;
}
}
}
} catch (IOException e1) {
System.out.println("Could not bind server on: " + port);
System.exit(-1);
}
}
}
And here is the rest:
import java.io.*;
import java.net.Socket;
public class MultiServer_Client implements Runnable {
public String time;
public Socket client;
public StringBuffer process = new StringBuffer();
public BufferedInputStream inputStream;
public InputStreamReader reader;
public BufferedOutputStream outputStream;
public OutputStreamWriter writer;
public StringVis check = new StringVis("");
public StringChangeListener checkListener = new StringChangeListener() {
public void textChanged(StringChangeEvent e) {
System.out.println("Changed");
write("Server recieved message...");
}
};
public boolean connected = true;
public int ID;
public MultiServer_Client(Socket connection, int i) {
client = connection;
ID = i;
try {
//declare text input/output
inputStream = new BufferedInputStream(client.getInputStream());
reader = new InputStreamReader(inputStream);
outputStream = new BufferedOutputStream(client.getOutputStream());
writer = new OutputStreamWriter(outputStream, "US-ASCII");
} catch (IOException e) {
System.out.println("IOException: " + e);
}
System.out.println(MultipleSocketServer.connected[ID] + " connected...");
write("Connected to " + MultipleSocketServer.name);
}
public void run() {
while(connected) {
read();
}
System.out.println("Disconnecting client...");
}
public void write(String authen) {
try {
time = new java.util.Date().toString();
String message = time + ": " + authen + (char) 13;
writer.write(message);
writer.flush();
} catch (IOException e) {
connected = false;
MultipleSocketServer.connected[ID] = "";
}
}
public void read() {
//read from client
int character;
process = new StringBuffer();
try {
while ((character = reader.read()) != 13) {
process.append((char) character);
}
check.setText(process.toString());
process.delete(0, process.length());
} catch (IOException e) {
connected = false;
MultipleSocketServer.connected[ID] = "";
}
}
}
Here's the client code:
import java.net.*;
import java.util.Scanner;
import java.io.*;
public class SocketClient {
public static String host = "69.182.134.79";
public static int port = 25565;
public static void main(String [] args) {
StringBuffer imports = new StringBuffer();
String time;
System.out.println("Client starting...");
try {
//establish client
InetAddress address = InetAddress.getByName(host);
Socket connection = new Socket(address, port);
BufferedOutputStream bos = new BufferedOutputStream(connection.getOutputStream());
OutputStreamWriter osw = new OutputStreamWriter(bos, "US-ASCII");
BufferedInputStream bis = new BufferedInputStream(connection.getInputStream());
InputStreamReader isr = new InputStreamReader(bis, "US-ASCII");
while(true) {
Scanner scan = new Scanner(System.in);
String message = scan.nextLine();
//write to server
time = new java.util.Date().toString();
String process = host + ":" + port + " sent data at " + time + ": " + message + (char) 13;
osw.write(process);
osw.flush();
//read from server
int c;
while ((c = isr.read()) != 13) {
imports.append((char) c);
}
System.out.println(imports);
imports.replace(0, imports.length(), "");
if(message.equals("--EXIT")) {
connection.close();
}
}
} catch (UnknownHostException e) {
System.out.println("UnknownHostException: " + e);
} catch (IOException e) {
System.out.println("IOExcepion: " + e);
}
}
}
Change
MultiServer_Client client = new MultiServer_Client(connection, i);
to
MultiServer_Client client = new MultiServer_Client(new Socket([Server IP], port), i);
This should work.

Categories