I'm trying to make a simple program with a server and client, passing text strings back and forth. I'm having trouble making the connection. I have a test printing line right below the socket accept line and it never prints, so I assume the problem is there, but I'm not sure how to do a more thorough check.
I have written this program in Eclipse if that makes a difference.
This is the server:
import java.io.*;
import java.net.*;
public class HW2Q1S {
public static void main(String[] args) throws Exception {
try {
//connection
ServerSocket srvr = new ServerSocket(7654);
Socket skt = srvr.accept();
System.out.println(skt.getPort());
//data xfer
BufferedReader sIn = new BufferedReader(new InputStreamReader(skt.getInputStream()));
PrintWriter sOut = new PrintWriter(skt.getOutputStream(), true);
//string receiving
int count = 1;
String msg = "";
while((msg = sIn.readLine()) != null) {
while(count < 11) {
msg = sIn.readLine();
System.out.println("Received: "+ msg);
String returnMsg = msg.toUpperCase();
System.out.println("Capped: "+ returnMsg);
sOut.write(returnMsg);
count++;
}
} //end of read from client in while loop
if (count == 10) {
System.out.println("Max reached.");
}
srvr.close();
return;
}
catch(Exception e) {
System.out.println("Error caught: " + e);
}
} // end of main
} // end of class
And this is the client:
import java.util.Random;
import java.io.*;
import java.net.*;
public class HW2Q1C {
public static void main(String[] args) throws IOException {
String capped = "";
String temp = "";
try {
//make the connection
Socket skt = new Socket("localhost", 7654);
BufferedReader cIn = new BufferedReader(new InputStreamReader(skt.getInputStream()));
PrintWriter cOut = new PrintWriter(skt.getOutputStream(), true);
//send 11 strings
for (int i = 0; i < 11; i++) {
temp = Stringer();
cOut.write(temp);
System.out.println("Sending: " + temp);
}
//receive server strings
while(cIn.readLine() != null) {
capped = cIn.readLine();
System.out.println("From server: "+ capped);
}
skt.close();
} // end of connection try block
catch(Exception e) {
System.out.print("Whoops! It didn't work!\n");
}
} //end of main
static String Stringer() {
String msg, alpha;
msg = "";
alpha = "abcdefghijklmnopqrstuvwxyz";
Random rnd = new Random();
for (int i = 0; i < 10; i++) {
msg += alpha.charAt(rnd.nextInt(25));
}
return msg;
}
} //end of class
Thanks!
I think I found your problem.
You should use println instead of write. I am quite sure the problem is that write does not send an actual line string + \n and therefore the server cannot read a line.
I modified your example a little bit to make it easier to test and understand, but this works for me:
Server:
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) throws Exception {
try {
//connection
ServerSocket srvr = new ServerSocket(7654);
Socket skt = srvr.accept();
System.out.println(skt.getPort());
BufferedReader in = new BufferedReader(new InputStreamReader(skt.getInputStream()));
String msg = "";
while ((msg = in.readLine()) != null) {
System.out.println("Received: " + msg);
} //end of read from client in while loop
srvr.close();
} catch (Exception e) {
System.out.println("Error caught: " + e);
}
} // end of main
} // end of class
Client:
import java.util.Random;
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) throws IOException {
try {
Socket socket = new Socket("localhost", 7654);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
for (int i = 0; i < 11; i++) {
out.println(Stringer()); //<-- println instead of write
}
socket.close();
} // end of connection try block
catch(Exception e) {
System.out.print(e.toString());
}
} //end of main
static String Stringer() {
String msg, alpha;
msg = "";
alpha = "abcdefghijklmnopqrstuvwxyz";
Random rnd = new Random();
for (int i = 0; i < 10; i++) {
msg += alpha.charAt(rnd.nextInt(25));
}
return msg;
}
} //end of class
ServerOutput:
Received: scnhnmaiqh
Received: tuussdmqqr
Received: kuofypeefy
Received: vghsinefdi
Received: ysomirnfit
Received: lbhqjfbdio
Received: qhcguladyg
Received: wihrogklfi
Received: tipikgfvsx
Received: fmpdcbtxqb
Received: yujtuefqft
Related
I'm coding socket client in Java.
In the program, I want to get information from server.
When the server receives "GET_LIGHTS" command, it sends back data in JSON format.
But in my code, bw.write() and bw.flush() doesn't work before socket.close().
So, the BufferedReader object is not ready: br.ready() returns false.
Is there any mistake in my code?
The client code is shown bellow.
package monitor;
import java.io.*;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.ArrayList;
public class SocketClient {
static private int port;
static private String hostName;
private Socket socket;
public SocketClient(String host, int port) {
this.hostName = host;
this.port = port;
}
// get lights by JSON
public void getLights() {
try {
// generate socket
InetSocketAddress endpoint = new InetSocketAddress(hostName, port);
socket = new Socket();
socket.connect(endpoint);
// setting
OutputStreamWriter out = new OutputStreamWriter(socket.getOutputStream());
BufferedWriter bw = new BufferedWriter(out);
InputStreamReader in = new InputStreamReader(socket.getInputStream());
BufferedReader br = new BufferedReader(in);
// send command
bw.write("GET_LIGHTS");
bw.flush();
// receive message from server
System.out.println(br.readLine());
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void initLights(ArrayList<Light> lights) {
getLights();
}
}
Edited:
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
public class SocketServer extends Thread{
static final int PORT = 44344;
static private ILS ils;
private ServerSocket serverSocket;
private Socket socket;
public SocketServer(ILS ils) {
this.ils = ils;
}
#Override
public void run() {
serverSocket = null;
System.out.println("Server: listening");
try {
serverSocket = new ServerSocket(PORT);
while(true){
socket = serverSocket.accept();
BufferedReader br = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
ArrayList<String> cmd = new ArrayList<>();
String in;
while( (in = br.readLine()) != null ){
cmd.add(in);
}
command(cmd);
if( socket != null){
socket.close();
}
}
} catch (IOException e) {
e.printStackTrace();
}
if( serverSocket != null){
try {
serverSocket.close();
serverSocket = null;
} catch (IOException e) {
e.printStackTrace();
}
}
}
// send message to client
private void sendMessage(String str) {
System.out.println(str);
try {
OutputStream output = socket.getOutputStream();
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(output));
bw.write(str + "¥n");
bw.flush();
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// error
private void printError(String err) {
String str = "ERROR; ";
str += err;
sendMessage(str);
}
public void command(ArrayList<String> cmd) {
String mode = cmd.get(0);
if(mode == null){
}else switch(mode){
case "MANUAL_SIG-ALL":
System.out.println("全照明一括 信号値指定調光");
manualSigAll(cmd.get(1));
break;
case "MANUAL_SIG-INDIVIDUAL":
System.out.println("全照明独立 信号値指定調光");
manualSigIndividual(cmd.get(1));
break;
case "MANUAL_ID-SIG":
System.out.println("照明ID・信号値指定調光");
manualIDSig(cmd.get(1));
break;
case "MANUAL_ID-RELATIVE":
System.out.println("照明ID・相対信号値指定調光");
break;
case "DOWNLIGHT_ALL":
System.out.println("Downlight: All Control");
downlightAll(cmd.get(1));
break;
case "DOWNLIGHT_INDIVIDUAL":
System.out.println("Downlight: Individual control");
downlightIndividual(cmd.get(1));
break;
case "GET_LIGHTS":
System.out.println("Sending lights via JSON");
sendLights();
break;
default:
System.out.println("Error: 不明なmode command");
}
}
// 全照明一括 信号値指定調光
private void manualSigAll(String sigs) {
if(sigs == null) {
System.out.println("信号値のフォーマットを確認してください");
} else {
ArrayList<Integer> s = new ArrayList<>();
String[] buf = sigs.split(",");
for(String i:buf) s.add(Integer.parseInt(i));
for(Light l: ils.getLights()) {
l.setLumPct((double)s.get(0)/255.0*100.0);
l.setSignal(s.get(0), s.get(1));
}
}
// 調光
ils.downlightDimmer.send();
}
// 全照明独立 信号値指定調光
private void manualSigIndividual(String sigs) {
if(sigs == null) {
System.out.println("信号値のフォーマットを確認してください");
} else {
ArrayList<Integer> s = new ArrayList<>();
String[] buf = sigs.split(",");
for(String i:buf) s.add(Integer.parseInt(i));
for(int i=0; i<ils.getLights().size(); i++) {
ils.getLights().get(i).setSignal(s.get(0), s.get(1));
s.remove(0);
s.remove(0);
}
}
ils.downlightDimmer.send();
}
// 照明ID・信号値指定調光
private void manualIDSig(String sigs) {
if(sigs == null) {
System.out.println("信号値のフォーマットを確認してください");
} else {
ArrayList<Integer> s = new ArrayList<>();
String[] buf = sigs.split(",");
for(String i:buf) s.add(Integer.parseInt(i));
System.out.println(s.get(0));
ils.getLight(s.get(0)).setSignal(s.get(1), s.get(2));
}
ils.downlightDimmer.send();
}
private void downlightAll(String cmd) {
if(cmd == null) {
printError("Check for data command.");
} else {
ArrayList<Double> data = new ArrayList<>();
String[] buf = cmd.split(",");
for(String i:buf) data.add(Double.parseDouble(i));
for(Light l: ils.getLights()) {
l.setLumPct(data.get(0));
l.setTemperature(data.get(1));
}
}
// dimming
ils.downlightDimmer.send();
}
private void downlightIndividual(String cmd) {
if(cmd == null) {
printError("Check for data command.");
} else {
ArrayList<Integer> id = new ArrayList<>();
ArrayList<Double> lumPct = new ArrayList<>();
ArrayList<Integer> temp = new ArrayList<>();
String[] buf = cmd.split(",");
if(buf.length % 3 != 0) {printError("invalid number of data.");}
for(int i=0; i<buf.length/3; i++) {
int n = i*3;
try {
id.add(Integer.parseInt(buf[n]));
lumPct.add(Double.parseDouble(buf[n + 1]));
temp.add(Integer.parseInt(buf[n + 2]));
} catch (Exception e) {
printError(e.getMessage());
return;
}
}
while (id.size() > 0) {
// update light object
Light light = ils.getLight(id.get(0));
light.setLumPct(lumPct.get(0));
light.setTemperature(temp.get(0));
// remove data from array list
id.remove(0);
lumPct.remove(0);
temp.remove(0);
}
// dimming
ils.downlightDimmer.send();
}
}
private void sendLights() {
ObjectMapper mapper = new ObjectMapper();
String json = "";
try {
json = mapper.writeValueAsString(ils.getLights());
} catch (JsonProcessingException e) {
e.printStackTrace();
}
// output
sendMessage(json);
}
}
If your server is using readLine(), as is probable, it will block until you close the connection, because you aren't sending a line.
Add bw.newLine() before the flush().
EDIT As predicted, your server isn't sending lines, so it needs the same treatment as above. However there is an anterior problem:
while( (in = br.readLine()) != null ){
cmd.add(in);
}
This loop in the server cannot possibly exit until the client closes the connection. You should process a line at a time in the server, or else moderate your expectations of the client's behaviour.
There is a string called numberPart inside a thread class called ServerRecieve. The location where .start() is being called is inside of a different class called Server.
The 'numberPart' will eventually be used as a port for file transferring later on.
My question is: How do I access the numberPart variable inside of the class called Server?
Screenshot of code running (server on left window, client on the right):
server on left window, client on the right
In the left window of the screenshot (server) you can see the that the first port number of the right window's command line argument which is 4021 being sent via a text message, and the server successfully receives it with the message "File transfer port found: 4021". Unfortunately this variable is located inside a different class. I would like to know how to access that variable inside the class called Server.
ServerRecieve code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
public class ServerRecieve extends Thread
{
Socket servSocket;
boolean m_bRunThread = true;
boolean ServerOn = true;
public ServerRecieve(Socket s)
{
super();
servSocket = s;
}
public void run()
{
while(true)
{
try
{
BufferedReader readFromClient = new BufferedReader(new InputStreamReader(servSocket.getInputStream()));
String fromClient = readFromClient.readLine();
String a = fromClient;
int i;
for(i = 0; i < a.length(); i++)
{
char c = a.charAt(i);
if( '0' <= c && c <= '9' )
{
break;
}
}
String alphaPart = a.substring(0, i);
String numberPart = a.substring(i);
System.out.println("Recieved from client: " + alphaPart +"\n");
System.out.println("File transfer port found: " + numberPart + "\n");
//String[] filePortNumber = null;
//filePortNumber[0] = numberPart;
// Server thing = new Server(filePortNumber);
if(fromClient.equals(null))
{
System.exit(0);
}
OutputOptions();
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
}
}
}
void OutputOptions()
{
System.out.println("Enter an option ('m', 'f', 'x'): ");
System.out.println("(M)essage (send)");
System.out.println("(F)ile (request) ");
System.out.println("e(X)it ");
}
}
Server source:
import java.io.*;
import java.net.*;
import java.util.*;
import javax.imageio.IIOException;
public class Server
{
private String[] serverArgs;
public Socket socket;
public Socket fileSocket;
public boolean keepRunning = true;
public int ConnectOnce = 0;
public String option = "";
public boolean isConnected = false;
public String FILE_TO_SEND = "/Users/nanettegormley/Documents/workspace/assignment2/src/servers/cdm.jpg";
public Server(String[] args) throws IOException
{
// set the instance variable
this.serverArgs = args;
if(ConnectOnce == 0)
{
int port_number1 = Integer.valueOf(serverArgs[1]);
ServerSocket serverSocket = new ServerSocket(port_number1);
socket = serverSocket.accept();
ConnectOnce = 4;
isConnected = true;
}
}
public String[] serverRun2(String[] args) throws IOException
{
serverArgs = args;
serverArgs = Arrays.copyOf(args, args.length);
serverSend.start();
return serverArgs;
}
Thread serverSend = new Thread()
{
public void run()
{
OutputOptions();
while(isConnected)
{
try
{
ServerRecieve serverThread = new ServerRecieve(socket);
serverThread.start();
// input the message from standard input
BufferedReader input2= new BufferedReader(new InputStreamReader(System.in));
option = input2.readLine();
if(option.equals("m") || option.equals("M"))
{
StandardOutput();
}
if(option.equals("f") || option.equals("F"))
{
FileTransferSend();
}
if(option.equals("x") || option.equals("X"))
{
System.exit(0);
}
}
catch ( Exception e )
{
System.out.println( e.getMessage() );
}
}
}
};
public void StandardOutput()
{
try
{
//Send the message to the server
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
//creating message to send from standard input
String newmessage = "";
try
{
System.out.println("Enter your message: ");
// input the message from standard input
BufferedReader input2= new BufferedReader(new InputStreamReader(System.in));
String line = "";
line= input2.readLine();
newmessage += line + " ";
}
catch ( Exception e )
{
System.out.println( e.getMessage() );
}
String sendMessage = newmessage;
bw.write(sendMessage + "\n");
bw.newLine();
bw.flush();
System.out.println("Message sent to client: "+sendMessage);
StandardInput();
//run();
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
}
}
void FileTransferSend()
{
//connect to the filetransfer
try
{
System.out.println("Which file do you want? ");
Scanner scanner = new Scanner(System.in);
String filename = scanner.nextLine();
FileInputStream fis = new FileInputStream(new File(filename));
DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(fileSocket.getOutputStream()));
int element;
while((element = fis.read()) !=1)
{
dos.write(element);
}
byte[] byteBuffer = new byte[1024]; // buffer
while(fis.read(byteBuffer)!= -1)
{
dos.write(byteBuffer);
}
OutputOptions();
// dos.close();
// fis.close();
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
}
}
void OutputOptions()
{
System.out.println("Enter an option ('m', 'f', 'x'): ");
System.out.println("(M)essage (send)");
System.out.println("(F)ile (request) ");
System.out.println("e(X)it ");
}
public void StandardInput()
{
OutputOptions();
while(true)
{
try
{
// input the message from standard input
BufferedReader input2= new BufferedReader(new InputStreamReader(System.in));
String line2 = "";
option= input2.readLine();
if(option.equals("m") || option.equals("M"))
{
StandardOutput();
}
if(option.equals("f") || option.equals("F"))
{
FileTransferSend();
}
if(option.equals("x") || option.equals("X"))
{
System.exit(0);
}
}
catch ( Exception e )
{
System.out.println( e.getMessage() );
}
finally
{
}
}
}
}
Full code with all files:
https://www.dropbox.com/s/0yq47gapsd3dgjp/folder33.zip?dl=0
My question is: What changes can I make to the code that would allow me to access numberPart while being inside Server?
EDIT: Is there a way to bump a question that hasn't gotten any answers or should I just delete this one and repost it somewhere?
I would think that you could use either a listener or callback pattern to solve this.
(I'm losing my Java memory now that I'm doing C# so please bear with me..)
interface PortAssignable {
public assignPort(int port);
}
Then have the Server class implement that interface
public Server implements PortAssignable {
...
}
And ServerReceive
// Constructor
public ServerRecieve(Socket s, PortAssignable portNotifyListener) {
_portNotifyListener = portNotifyListener;
... your other code ...
}
Make sure when you create an instance of ServerReceive, you pass in your Server instance, via this.
ServerRecieve serverThread = new ServerRecieve(socket, this);
Now, when you get your numberPart, your next line can be
_portNotifyListener.assignPort(numberPart);
How you choose to implement the assignPort method in your Server class is up to you.
P.S. I saw this question from /r/programming.
Have a task to create a basic http server. I've gotten to the point where it asks you to send text response back that should be displayed in your browser if you go to http://localhost:8080/ but I just get a page cannot be displayed error. I think it must be something to do with the format of the response I'm sending but i just can't get it. Any help would be much appreciated.
import java.net.*;
import java.io.*;
import java.util.*;
class HttpServer{
public static void main(String[] args){
try{
ServerSocket ss = new ServerSocket(8080);
while(true){
HttpServerSession sesh = new HttpServerSession(ss.accept());
sesh.start();
}
}catch(IOException e){
System.err.println("IOException");
}
}
}
class HttpServerSession extends Thread {
private Socket client;
public HttpServerSession(Socket client){
this.client = client;
}
private void println(BufferedOutputStream bos, String s) throws IOException {
String news = s + "\r\n";
byte[] array = news.getBytes();
for(int i = 0; i < array.length; i++){
bos.write(array[i]);
}
return;
}
public void run(){
try{
InetAddress clientIP = client.getInetAddress();
System.out.println("We just got a message! " + clientIP.getHostAddress());
BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
String request = reader.readLine();
System.out.println(request);
String[] parts = request.split(" ");
if(parts.length == 3){
BufferedOutputStream bos = new BufferedOutputStream(client.getOutputStream());
String filename = parts[1].substring(1);
if(parts[0].equals("GET")){
while(true){
String line = reader.readLine();
System.out.println(line);
if(line == null || line.equals("")){
break;
}
}
println(bos, "OK");
println(bos, "");
println(bos, "Hello World");
}
}
client.close();
}catch(Exception e){
System.err.println("Exception in thread");
}
}
}
Turns out I just had to flush the BufferedOutputStream
Was writing a server for my X O game. The basic idea was that I have one computer run as a server wit ha static ip and others could connect to it.
It needs to be able to send the state of the game to all the connected clients, but I ran into a blocking problem.
If you take a look at the client side
Scanner input = new Scanner();
int test = input.nextInt();
is blocking the code.
The server is able to send the message to all the clients but it is being prevented by the nextInt() as it waits for the Int to be passed in order to echo the state of the game(jsut a set of ints, coordinates).
Could anyone help me out here, I am really stuck, have been reading up on blocking problems, on the net and here on the forums I found that some people were saying that I have to check the inputStream on the client side whether it contains something or not but I could not implement it.
Any idea, suggestions are welcomed.
Thank you all for your time.
-------SERVER-----------
import java.net.*;
import java.io.*;
public class Server extends SerResponse {
public static void main(String[] args) {
int port = 1234;
int cliNum = 1;
try {
ServerSocket sock = new ServerSocket(port);
System.out.println("SERVER WORKING......");
int index0 = 0;
while (true) {
SerResponse ser = new SerResponse();
Socket connection = sock.accept();
soc[index0] = connection;
index0++;
if (connection != null) {
System.out.println("Client " + cliNum + " connected " + connection);
cliNum++;
}
Runnable runnable = new Server(connection, ++ser.count);
Thread t = new Thread(runnable);
t.start();
}
} catch (Exception e) {
System.out.println("SERVER FAIL " + e);
}
}
public Server(Socket s, int count) {
this.connection = s;
this.ID = count;
}
}
------SERVER RESPONSE--------------
import java.io.*;
import java.net.Socket;
public class SerResponse implements Runnable {
public static Socket connection;
public int ID;
public final static int size = 10;
public static Socket[] soc = new Socket[size];
public int count = 0;
public int test;
public void run() {
try {
while (true) {
DataInputStream in = new DataInputStream(connection.getInputStream());
test = in.readInt();
System.out.println("Recieved from " + connection + " " + test + "\n");
for (int index0 = 0; index0 < size; index0++) {
if (soc[index0] != null) {
DataOutputStream out = new DataOutputStream(soc[index0].getOutputStream());
out.writeInt(test);
System.out.println("Sent to client " + soc[index0] + " " + test);
}
}
}
} catch (Exception e) {
System.out.println("Runnable FAIL " + e);
}
}
}
-----CLIENT--------
import java.net.*;
import java.util.Scanner;
import java.io.*;
public class client {
public static void main(String[] args) {
int[][] arr = {{3, 4}, {6, 2}, {9, 2}};
int[][] arr1 = new int[3][2];
int port = 1234;
int test;
int test1;
try {
System.out.println("Starting client");
Socket sock = new Socket("localhost", port);
DataOutputStream out = new DataOutputStream(sock.getOutputStream());
DataInputStream in = new DataInputStream(sock.getInputStream());
Scanner input = new Scanner(System.in);
int turn = 0;
while (true) {
test = input.nextInt();
out.writeInt(test);
System.out.println(test);
test1 = in.readInt();
System.out.println(test1);
turn++;
}
} catch (Exception e) {
System.out.println("CLIENT FAIL " + e);
}
}
}
Here's a rework of your client class that should give the asynchronous behaviour that you're looking for.
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.Socket;
import java.util.Scanner;
public class Client extends Thread {
private final Socket sock;
private boolean shutdown = false;
public Client(Socket sock) {
this.sock = sock;
}
public void shutdown() {
shutdown = true;
}
public void writeDataToServer(int test) {
try {
synchronized(Client.class) {
//don't allow reading and writing at the same time.
DataOutputStream out = new DataOutputStream(sock.getOutputStream());
out.writeInt(test);
sock.getOutputStream().flush();
}
}catch(Exception e) {
e.printStackTrace();
}
}
#Override
public void run() {
try {
BufferedInputStream bis = new BufferedInputStream(sock.getInputStream());
while(!shutdown) {
if(bis.available() > 0) {
synchronized(Client.class) {
DataInputStream in = new DataInputStream(bis);
int test = in.readInt();
//you can do something with test hereafter.... but since the example just had it printing out
System.out.println(test);
}
} else {
Thread.sleep(500); //sleep for 500ms before polling again.
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
sock.close();
} catch(Exception ignored){}
}
}
public static void main(String[] args) {
int[][] arr = {{3, 4}, {6, 2}, {9, 2}};
int[][] arr1 = new int[3][2];
int port = 1234;
int test;
try {
System.out.println("Starting client");
Client client = new Client(new Socket("localhost", port));
client.start();
Scanner input = new Scanner(System.in);
int turn = 0;
while(turn < 10) {
test = input.nextInt();
client.writeDataToServer(test);
System.out.println(test);
turn++;
}
client.shutdown();
} catch(Exception e) {
System.out.println("CLIENT FAIL " + e);
}
}
}
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.