I am trying to run the code in a windows comman line and received exception :
D:\dasi\java\javaLab>java ServerClient
java.net.ConnectException: Connection refused: connect
java.lang.StringIndexOutOfBoundsException: String index out of range: -2
D:\dasi\java\javaLab>
in another command line windw :
D:\dasi\java\javaLab>java SocketClient
java.net.ConnectException: Connection timed out: connect
D:\dasi\java\javaLab>
Server code :
import java.io.*;
import java.net.*;
public class ServerClient {
public ServerClient(int port) {
Server server = new Server(port);
server.start();
Client client = new Client(port);
client.start();
}
public static void main(String[] args) {
ServerClient s1 = new ServerClient(7777);
}
}
class Server extends Thread {
int port;
ServerSocket server;
Socket socket;
DataOutputStream outStream = null;
DataInputStream inStream = null;
public Server(int poort) {
try {
this.port = port;
server = new ServerSocket(port);
}
catch(Exception e) {
System.out.println(e.toString());
}
}
public void run() {
try {
socket = server.accept();
outStream = new DataOutputStream(socket.getOutputStream());
inStream = new DataInputStream(socket.getInputStream());
System.out.println("server is ok, please continue!");
while(true) {
String str = inStream.readUTF();
System.out.println("The server receive String:"+str);
outStream.writeUTF(str);
}
}
catch(Exception e) {
System.out.println(e.toString());
}
}
}
class Client extends Thread {
int port;
Socket socket;
DataInputStream inStream = null;
DataOutputStream outStream = null;
public Client(int port) {
try {
this.port = port;
socket = new Socket(InetAddress.getLocalHost(),port);
inStream = new DataInputStream(socket.getInputStream());
outStream = new DataOutputStream(socket.getOutputStream());
System.out.println("client is ok, please continue!");
}
catch(Exception e) {
System.out.println(e.toString());
}
}
public void run() {
try {
while(true) {
byte[] b = new byte[1024];
String str = "";
int m = System.in.read(b);
str = new String(b,0,0,m-1);
outStream.writeUTF(str);
str = inStream.readUTF();
System.out.println("The client receive String:"+str);
}
}
catch(Exception e) {
System.out.println(e.toString());
}
}
}
Client code :
import java.net.*;
import java.io.*;
public class SocketClient {
Socket s = null;
DataInputStream inStream = null;
DataOutputStream outStream = null;
public SocketClient() {
try {
init();
waitData();
}
catch(Exception e) {
System.out.println(e.toString());
}
}
void init() throws Exception {
s=new Socket("10.15.43.216",8765);
inStream = new DataInputStream(s.getInputStream());
outStream = new DataOutputStream(s.getOutputStream());
s.setSoTimeout(3000);
}
void waitData() {
while(true) {
try {
String str = inStream.readUTF();
System.out.println("Client accept:" +str);
str = Integer.toString(Integer.parseInt(str)+1);
outStream.writeUTF(str);
}
catch(Exception e) {
System.out.println(e.toString());
break;
}
}
}
public static void main(String[] args) {
new SocketClient();
}
}
I am wodering if there's anything wrong in my code or if it was my computer port that cause the problem. Because when I checked my computer port I didn't see 7777. When I issued command netstat -nao | findstr 7777, it returned nothing.
D:\dasi\java\javaLab>netstat -nao | findstr 7777
D:\dasi\java\javaLab>
If it was the port problem, then how to open the 7777 port.
I am a newbie here, please help. Thanks a lot!
replace
public Server(int poort) {
try {
this.port = port;
...
}
}
with
public Server(int poort) {
try {
this.port = port;
...
}
}
or rather the default value of port is zero, then your serverSocket will bind with 0 port rather than 7777.
and as for this code segment:
public ServerClient(int port) {
Server server = new Server(port);
server.start();
Client client = new Client(port);
client.start();
}
I am afraid it is easy to make you in trouble, because we cant ensure the server thread will execute before client thread and if client thread execute first when server havent run it will cause error. And you already have a client in another java file, so I cant understand why you have an Client here. Maybe you could remove them, the code can be this:
public ServerClient(int port) {
Server server = new Server(port);
server.start();
}
as for Client Code
your server socket is 7777 so you should connect 7777 port rather than 8765 in you init method maybe the code can be this:
void init() throws Exception {
s=new Socket(server name,7777);
...
}
Related
I'm planning to create a server and run it on google cloud VM, this code is working fine in the localhost but it won't run on External IP.
import java.net.*;
import java.io.*;
public class Server extends Thread {
private ServerSocket serverSocket;
public Server(int port) throws IOException {
serverSocket = new ServerSocket(port);
}
public void run() {
while(true) {
try {
System.out.println("Waiting for Connection ");
Socket server = serverSocket.accept();
System.out.println("Just connected to " + server.getRemoteSocketAddress());
DataInputStream in = new DataInputStream(server.getInputStream());
System.out.println(in.readUTF());
DataOutputStream out = new DataOutputStream(server.getOutputStream());
out.writeUTF("Goodbye");
server.close();
} catch (SocketTimeoutException s) {
System.out.println("Socket timed out!");
break;
} catch (IOException e) {
e.printStackTrace();
break;
}
}
}
public static void main(String [] args) throws UnknownHostException {
int port = 4999;
try {
Thread t = new Server(port);
t.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
and this is for the client
import java.net.*;
import java.io.*;
public class Client {
public static void main(String [] args) {
String serverName = "localhost";
int port = Integer.parseInt("4999");
try {
System.out.println("Connecting to " + serverName + " on port " + port);
Socket client = new Socket(serverName, port);
OutputStream outToServer = client.getOutputStream();
DataOutputStream out = new DataOutputStream(outToServer);
out.writeUTF("[Client]Hello from " + client.getLocalSocketAddress());
InputStream inFromServer = client.getInputStream();
DataInputStream in = new DataInputStream(inFromServer);
System.out.println("[Server] " + in.readUTF());
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
and this is the net config of the google VM instance:
Internal ip-> 10.138.0.13 (nic0) | External ip-> 34.83.94.126
can you please tell me how to get it running on a public ip.
So I have a client:
public class TalkClient extends Thread
{
private int port;
private String host;
DocCntl theDocCntl;
public TalkClient(String host, int port) throws IOException
{
this.host = host;
this.port = port;
theDocCntl = new DocCntl(this);
}
public void run()
{
try
{
System.out.println("Seeking connection...");
Socket socket = new Socket(host, port);
DataInputStream in = new DataInputStream(socket.getInputStream());
BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
}catch(IOException e)
{
e.printStackTrace();
}
}
public static void main(String [] args)
{
int port = 5050;
try
{
Thread t = new TalkClient("127.0.0.1", port);
t.start();
}catch(IOException e)
{
e.printStackTrace();
}
}
public void pushToServer(){
String theData = this.theDocCntl.theDoc.docTA.getText();
}
}
And I have a server:
public class TalkServer extends Thread
{
private ServerSocket serverSocket;
public static DocCntl theCntl;
public TalkServer(int port) throws IOException
{
serverSocket = new ServerSocket(port);
}
public void run()
{
try
{
System.out.println("Listening for connections...");
Socket client = serverSocket.accept();
DataInputStream in = new DataInputStream(client.getInputStream());
BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
DataOutputStream out = new DataOutputStream(client.getOutputStream());
}catch(IOException e)
{
e.printStackTrace();
}
}
public static void main(String [] args)
{
int port = 5050;
try
{
Thread t = new TalkServer(port);
t.start();
}catch(IOException e)
{
e.printStackTrace();
}
}
}
In the client, I have a method called pushToServer, which I want to take the String data from a textArea on the client, and then push that to all the other connected clients. But I'm not sure how to handle sending the message to each individual connected client through the sockets. I've given it some thought, and I think I need to do 3 things:
1) Create and maintain a list of connected clients(threads). In the server class itself? Or in another class?
2) On the server, have some means of 'catching' the String data from one client, and then pushing it to all the other clients. This is why(I think) I need the list of clients. If I can figure out how to catch this(maybe through the input stream?) and then iterate through the list of clients to their text areas.
3) On the client side, I need to be able to catch the string from the server.
Any help on these 3 things would be greatly appreciated.
This is a simple client-server program. It works fine when executed in a single computer. But, it doesn't work when executed in two different laptops connected using WiFi.
Here's the code:
Server:
public class Server
{
private static int port;
private ServerSocket serverSocket;
public void GreetingServer(int port) throws IOException
{
serverSocket = new ServerSocket(port);
serverSocket.setSoTimeout(20000);
while(true)
{
try
{
System.out.println("Waiting for client");
Socket server = serverSocket.accept();
System.out.println("Connected");
DataInputStream in =new DataInputStream(server.getInputStream());
System.out.println(in.readUTF());
DataOutputStream out = new DataOutputStream(server.getOutputStream());
out.writeUTF("Thank you for connecting to ");
server.close();
}
catch(SocketTimeoutException s)
{
System.out.println("Socket timed out!");
break;
}
catch(IOException e)
{
e.printStackTrace();
break;
}
}
}
public static void main(String [] args)
{
port=9001;
try
{
Server s=new Server();
s.GreetingServer(port);
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
Client:
public class Client
{
private static String serverName;
public static void main(String [] args)
{
String sName = "192.168.xxxx.x";
int port = 9001;
try
{
System.out.println("Connecting to " + sName
+ " on port " + port);
Socket client = new Socket(sName, port);
System.out.println("Connected");
OutputStream outToServer = client.getOutputStream();
DataOutputStream out = new DataOutputStream(outToServer);
out.writeUTF("Hello from " + client.getLocalSocketAddress());
InputStream inFromServer = client.getInputStream();
DataInputStream in = new DataInputStream(inFromServer);
System.out.println("Server says " + in.readUTF());
client.close();
}catch(IOException e)
{
}
}
}
What could be the problem? Please me..
Thanks in advance..
The following code is correct when compiled, but when run it says: ConnectException
the error image:
import java.net.*;
import java.io.*;
class TcpChat
{
public static void main(String[] args) throws Exception
{
Socket s = new Socket("Ip",20000);
ServerSocket ss = new ServerSocket(20000);
new Thread(new TcpClient(s)).start();
new Thread(new TcpServer(ss)).start();
}
}
class TcpClient implements Runnable
{
Socket s;
TcpClient(Socket s)
{
this.s = s;
}
public void run()
{
try
{
OutputStream out = s.getOutputStream();
out.write("hello javaserver".getBytes());
s.close();
}
catch (Exception e)
{
}
}
}
class TcpServer implements Runnable
{
ServerSocket ss;
TcpServer(ServerSocket ss)
{
this.ss = ss;
}
public void run()
{
try
{
Socket s = ss.accept();
InputStream in = s.getInputStream();
byte[] buf =new byte[1024];
int length =in.read(buf);
String ip =s.getInetAddress().getHostAddress();
String data = new String(buf,0,length);
System.out.println(ip+":::"+data);
s.close();
ss.close();
}
catch (Exception e)
{
}
}
}
Additionally, there is no error about the IP address I use, in my PC I use my own IP.
You didn't post your whole code, so it's hard to check, but it seems like you try to connect to a port (i.e. open the client socket) before you actually open the server socket. That won't work, of course, since there's nothing listening at that port yet (thus: connection refused).
Change your main method like
ServerSocket ss = new ServerSocket(20000);
Socket s = new Socket("127.0.0.1", 20000);
new Thread(new TcpServer(ss)).start();
new Thread(new TcpClient(s)).start();
You can find a better example for Chat Server here. Also you can read about sockets from here
I've just started with this section of the tutorial. I only have a basic understanding of what ports are, etc.
I tried to run this code:
import java.io.*;
import java.net.*;
public class EchoClient {
public static void main(String[] args) throws IOException {
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
echoSocket = new Socket("taranis", 7);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
echoSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: taranis.");
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for "
+ "the connection to: taranis.");
System.exit(1);
}
BufferedReader stdIn = new BufferedReader(
new InputStreamReader(System.in));
String userInput;
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
System.out.println("echo: " + in.readLine());
}
out.close();
in.close();
stdIn.close();
echoSocket.close();
}
}
"Don't know about host: taranis.
Java Result: 1"
Is the error catch I get. From my limited understanding; is the echo-server something which exists on my machine? If that's the case, what do I need to do to get this running? Or am I way off?
Also why have they chosen "taranis" as a parameter?
Ive also replaced "taranis" with "localhost" to see what happened.
It ended up catching an IOException this time.
EDIT: So I've found that the echo server is disabled by default in win7 and have activated it. However I cant even connect to it on telnet. I think I may just be in over my head. I've also tried the sockets you have recommended with no success.
From the same tutorial:
... The Socket constructor used here requires the name of the machine and the port number to which you want to connect. The example program uses the host name taranis. This is the name of a hypothetical machine on our local network. When you type in and run this program on your machine, change the host name to the name of a machine on your network. Make sure that the name you use is the fully qualified IP name of the machine to which you want to connect. The second argument is the port number. Port number 7 is the port on which the Echo server listens.`
In any case, you will probably want to change taranis to "localhost" and make sure an echo service is running on your machine. If it's not, you could use something like the following code to simulate an echo server.
import java.net.Socket;
import java.util.Formatter;
import java.util.Scanner;
import java.io.IOException;
import java.net.ServerSocket;
import java.util.ArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class EchoServer {
public static void main(String[] args) {
try {
new EchoServer(INSERTPORT).execute();
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
}
private ServerSocket serverSocket;
private int port;
private ArrayList<Client> clientList;
private ExecutorService clientRunner;
public EchoServer(int port) throws IOException {
this.port = port;
serverSocket = new ServerSocket(port);
clientRunner = Executors.newCachedThreadPool();
clientList = new ArrayList<>();
}
public void sendMessageToAll(String message) {
for (Client c : clientList) {
c.displayMessage(message);
}
}
public void execute() throws IOException {
while (true) {
clientList.add(new Client(serverSocket.accept(), this));
clientRunner.execute(clientList.get(clientList.size()-1));
}
}
private class Client implements Runnable {
private Socket clientSocket;
private Scanner input;
private Formatter output;
public Client(Socket s) throws IOException {
clientSocket = s;
input = new Scanner(clientSocket.getInputStream());
output = new Formatter(clientSocket.getOutputStream());
}
public void displayMessage(String s) {
output.format(s + "\n");
output.flush();
}
#Override
public void run() {
while(clientSocket.isConnected()) {
if(input.hasNextLine()) {
sendMessageToAll(input.nextLine());
}
}
}
}
}
Edit: Just for completeness, as you mentioned some problems running the code, you run the server (this code) and leave it running in the background, then run the client (the code you posted). I tested it, works fine.
Try this,
Use the loopback address of 127.0.0.1 instead of taranis.
Use port higher than 1024, something like 4444, 8333 etc....
I am also adding my code that i used to learn Client Server Commnu
Client Side Code:
public class ClientWala {
public static void main(String[] args) throws Exception{
Boolean b = true;
Socket s = new Socket("127.0.0.1", 4444);
System.out.println("connected: "+s.isConnected());
OutputStream output = s.getOutputStream();
PrintWriter pw = new PrintWriter(output,true);
// to write data to server
while(b){
if (!b){
System.exit(0);
}
else {
pw.write(new Scanner(System.in).nextLine());
}
}
// to read data from server
InputStream input = s.getInputStream();
InputStreamReader isr = new InputStreamReader(input);
BufferedReader br = new BufferedReader(isr);
String data = null;
while ((data = br.readLine())!=null){
// Print it using sysout, or do whatever you want with the incoming data from server
}
}
}
Server Side Code:
public class ServerTest {
ServerSocket s;
public void go() {
try {
s = new ServerSocket(44457);
while (true) {
Socket incoming = s.accept();
Thread t = new Thread(new MyCon(incoming));
t.start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
class MyCon implements Runnable {
Socket incoming;
public MyCon(Socket incoming) {
this.incoming = incoming;
}
#Override
public void run() {
try {
PrintWriter pw = new PrintWriter(incoming.getOutputStream(),
true);
InputStreamReader isr = new InputStreamReader(
incoming.getInputStream());
BufferedReader br = new BufferedReader(isr);
String inp = null;
boolean isDone = true;
System.out.println("TYPE : BYE");
System.out.println();
while (isDone && ((inp = br.readLine()) != null)) {
System.out.println(inp);
if (inp.trim().equals("BYE")) {
System.out
.println("THANKS FOR CONNECTING...Bye for now");
isDone = false;
s.close();
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
try {
s.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
e.printStackTrace();
}
}
}
public static void main(String[] args) {
new ServerTest().go();
}
}