Socket instance wont connect to local server - java

I'm new to socket programming/networking in general. I'm trying to create a simple IRC that's an echo server. I'm using 127.0.0.1 and port 8080 for my socket object but I keep getting a ConnectionException. Does it have to do with me not setting anything up on my computer to allow connections?
Client class (I need to make a Server class maybe that handles allowing connections?)
package client.build;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.*;
import java.util.Scanner;
public class Client {
private static Socket socket;
private static DataInputStream inputStream;
private static DataOutputStream outputStream;
// This might not be needed
private static Scanner input = new Scanner(System.in);
private final String[] arguments;
public Client(String[] arguments) throws IOException {
this.arguments = arguments;
}
public void connect() throws IOException, InterruptedException {
try {
socket = new Socket(arguments[0], Integer.parseInt(arguments[1]));
inputStream = new DataInputStream(System.in);
outputStream = new DataOutputStream(socket.getOutputStream());
} catch(ConnectException e) {
System.out.println("failed to connect to echo server");
Thread.sleep(600);
System.exit(0);
}
}
}

Few things to check:
You are trying to create echo server, which means that you need to listen on 8080 instead of connecting to 8080?
ServerSocket serverSocket = new ServerSocket(8080);
Socket clientSocket = serverSocket.accept();
Assuming that your code is actually the IRC client. Do you have something that listens on port 8080 on 127.0.0.1? Try using netstat to verify that it is listening on 127.0.0.1:8080
Check that arguments[0] is really 127.0.0.1. You can try with the null for localhost

Related

Run running TCP and UDP server at the same time

I have a network programming topic that requires file transfer using TCP and UDP. If TCP send fails then UDP will be executed. I have built each part but I am not sure how can I run the server of TCP and UDP at the same time to be able to receive data of both protocols (my problem is starting 2 server in the master server because I have as the interface). Hope everybody help please .
In one case you need to open a ServerSocket, in the other case a DatagramSocket. It should be possible to open them in parallel, which means you can run both your implementations in parallel running on different threads.
If you are suppose to run the TCP and the UDP Server on the same machine, you will need to use different ports. Then you can start up two different thread, one for each server:
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.stream.Collectors;
public class TcpUdpServer {
private final static int UDP_PORT = 8100;
private final static int TCP_PORT = 8200;
public static void main(String[] args) {
new Thread(() -> executeTcpServer()).start();
new Thread(() -> executeUdpServer()).start();
}
public static void executeTcpServer() {
try (ServerSocket serverSocket = new ServerSocket(TCP_PORT)) {
while (true) {
System.out.println("waiting for TCP connection...");
// Blocks until a connection is made
final Socket socket = serverSocket.accept();
final InputStream inputStream = socket.getInputStream();
String text = new BufferedReader(
new InputStreamReader(inputStream, StandardCharsets.UTF_8))
.lines()
.collect(Collectors.joining("\n"));
System.out.println(text);
}
} catch (Exception exception) {
exception.printStackTrace();
}
}
public static void executeUdpServer() {
try (DatagramSocket socket = new DatagramSocket(UDP_PORT)) {
while (true) {
byte[] packetBuffer = new byte[2024];
final DatagramPacket packet = new DatagramPacket(packetBuffer, packetBuffer.length);
System.out.println("waiting for UDP packet...");
// Blocks until a packet is received
socket.receive(packet);
final String receivedPacket = new String(packet.getData()).trim();
System.out.println(receivedPacket);
}
} catch (Exception exception) {
exception.printStackTrace();
}
}
}

Can't connect Java sockets

I'm trying to connect two simple Java sockets but whatever port number I type I get the same error : Address already in use: JVM_Bind
Now I found I way around the problem by using using 0 as an argument to the ServerSocket constructor and then calling the getLocalPort method to get the first available port and then pass it to my client class in the Socket constructor as an argument.
So, in NetBeans IDE, I first run the server, get the available port from the console, copy the number and manually enter it to the Socket constructor as the second argument after "localhost" and run the client.
Now the expected output would be "Connected" as the server has accepted the client, but instead, I get the available port number incremented by 1.
Why is this happening? It seems that when I click run in my client.java file I start the server again instead of the client.
sever.java
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class server {
public static void main(String[] args) throws IOException {
ServerSocket s1 = new ServerSocket(58801);/I manually add the available port number here
System.out.println(s1.getLocalPort());
Socket ss = s1.accept();
System.out.println("Client connected");
}
}
client.java :
import java.io.IOException;
import java.net.Socket;
public class client {
public static void main(String[] args) throws IOException {
Socket s = new Socket("localhost", 58801); // I here manually add the available port number
}
}
A somewhat belated answer, after the OP already figured it out:
One possible cause is running the server twice by mistake in the IDE. The first run grabs the port, the second run of the server will find that port already in use and generate the error.
An example of Server client socket:
Server class:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class GreetServer {
private ServerSocket serverSocket;
private Socket clientSocket;
private PrintWriter out;
private BufferedReader in;
public void start(int port) throws IOException {
serverSocket = new ServerSocket(port);
clientSocket = serverSocket.accept();
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String greeting = in.readLine();
if ("hello server".equals(greeting)) {
out.println("hello client");
} else {
out.println("unrecognised greeting");
}
}
public void stop() throws IOException {
in.close();
out.close();
clientSocket.close();
serverSocket.close();
}
public static void main(String[] args) throws IOException {
GreetServer server = new GreetServer();
server.start(6666);
}
}
Client class:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class GreetClient {
private Socket clientSocket;
private PrintWriter out;
private BufferedReader in;
public void startConnection(String ip, int port) throws IOException {
clientSocket = new Socket(ip, port);
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
}
public String sendMessage(String msg) throws IOException {
out.println(msg);
String resp = in.readLine();
return resp;
}
public void stopConnection() throws IOException {
in.close();
out.close();
clientSocket.close();
}
public static void main(String[] args) throws IOException {
GreetClient client = new GreetClient();
client.startConnection("127.0.0.1", 6666);
String response = client.sendMessage("hello server");
System.out.println("Response from server: " + response);
}
}
Example response:
Response from server: hello client

Java socket programming: server thread will not receive request from client (connection times out)

I have a server class file that is compiled and executed in a remote linux machine, to which I'm connected via PuTTY
I have a client class file in my local windows 10 machine, which I compile and execute using the built-in command prompt
Server class
import java.net.*;
import java.io.*;
public class ServerTest {
public static void main(String[] args) {
try {
ServerSocket serv = new ServerSocket(Integer.parseInt(args[0]));
InetAddress ia = InetAddress.getLocalHost();
System.out.println(ia.getHostName());
System.out.println(ia.getHostAddress());
Socket client = serv.accept();
PrintWriter pw = new PrintWriter(client.getOutputStream(), true);
pw.println("Server says Hello, world!");
} catch (Exception e) {e.printStackTrace();}
}
}
running java ServerTest 5000 in the remote linux machine starts the server thread listening on port 5000 and prints the host name and IP address to the prompt. I later pass the name/address to the client to attempt to make a connection.
Now, the client class
import java.net.*;
import java.io.*;
public class ClientTest {
public static void main(String[] args) {
String host = args[0];
int port = Integer.parseInt(args[1]);
try {
Socket sock = new Socket(host, port);
PrintWriter pw = new PrintWriter(sock.getOutputStream(), true);
BufferedReader reader = new BufferedReader(
new InputStreamReader(
sock.getInputStream()));
System.out.println(reader.readLine());
} catch (IOException e) {e.printStackTrace();}
}
}
running java ClientTest [host name/address] 5000 on the local machine will attempt to connect to the server socket for a few seconds before crashing with a Connection timed out error. I tried using both the host name and IP address as the first argument. From what I can tell, the client does send a request and the server does begin listening, but the server never receives the request. I don't know what I'm doing wrong and I appreciate any help!

Android Client/Server socket confusion concept on moving forward

I'm trying to learn about client/server and sockets right now but I'm confused on the bigger scope of things. I followed a tutorial that has a client as an android app and the server is a java application. I run both of them on eclipse fine.
My question now is how do I make this global? So I'll take my server code written in java, export it to a text called server.java, and then upload it to my personal site? And then when I start my client android app, I'll make a call to say http://blah.com/server.java to start my server, right? Then my server will begin listening on that port and my client can connect to it?
Server:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
public class SimpleTextServer {
private static ServerSocket serverSocket;
private static Socket clientSocket;
private static InputStreamReader inputStreamReader;
private static BufferedReader bufferedReader;
private static String message;
public static void main(String[] args) {
try {
serverSocket = new ServerSocket(4444); // Server socket
} catch (IOException e) {
System.out.println("Could not listen on port: 4444");
}
System.out.println("Server started. Listening to the port 4444");
while (true) {
try {
clientSocket = serverSocket.accept(); // accept the client connection
inputStreamReader = new InputStreamReader(clientSocket.getInputStream());
bufferedReader = new BufferedReader(inputStreamReader); // get the client message
message = bufferedReader.readLine();
System.out.println(message);
//will later add an output stream to write back to android
inputStreamReader.close();
clientSocket.close();
} catch (IOException ex) {
System.out.println("Problem in message reading");
}
}
}
}

How to correctly close a socket and then reopen it?

I'm developing a game for a class that I am in, and it is about 99% done. However, I realized there is a problem: If the server and client disconnect, and the client attempts to reconnect (and the server is back up and running fine), the client is not making a new connection.
The server and client are both multi-threaded. If I send the client a Kick message, what happens is the client will close its socket. If I reconnect, I get a SocketException: socket closed even though whenever connect is pressed, a new Client is constructed, which is basically just a class that creates a socket and connects to the server with a get/send thread.
Do you think there is anything I am doing illogically? It is like it is attempting to use the old Socket and Client that were constructed, but if I do some println calls, I can see that it does construct a new one and they are in different memory locations.
Thanks!
After closing a socket, you cannot reuse it to share other data between Server and Client classes. From the Java Socket API, about close() method's description:
Any thread currently blocked in an I/O operation upon this socket will
throw a SocketException.
Once a socket has been closed, it is not available for further
networking use (i.e. can't be reconnected or rebound). A new socket
needs to be created.
Closing this socket will also close the socket's InputStream and
OutputStream.
If this socket has an associated channel then the channel is closed
as well.
Then, it isn't possible to close a socket and reopen it. That's the reason, I think, of the exception being thrown.
It can be easy! I made this program (server side):
import java.net.ServerSocket;
import java.net.Socket;
import java.io.DataInputStream;
import java.io.DataOutputStream;
public class Host{
public static void main(String[] args) throws Exception{
while(true){
ServerSocket ss = new ServerSocket(1300);
Socket s = ss.accept();
DataInputStream din = new DataInputStream(s.getInputStream());
String msgin = din.readUTF();
System.out.println(msgin);
ss.close();
s.close();
din.close();
}
}
}
Client side:
import java.net.Socket;
import java.io.DataInputStream;
import java.io.DataOutputStream;
public class Client{
public static void main(String[] args) throws Exception{
while(true){
Socket s = new Socket("localhost", 1300);
DataOutputStream dout = new DataOutputStream(s.getOutputStream());
dout.writeUTF("hello");
s.close();
dout.close();
}
}
}
It works, beacuse you can declare tons of Sockets with the same ServerSocket, so for example this works too:
ServerSocket ss = new ServerSocket(1300);
Socket a = ss.accept();
Socket b = ss.accept();
Socket c = ss.accept();
and you have 3 Sockets...
Remember: java waits for a client to connect when you declare a Socket!
Code:
Client:
import java.net.Socket;
public class client {
public static void main(String[] args) throws Exception{
Socket a = new Socket("localhost", 1300);
Thread.sleep(3000);
Socket b = new Socket("localhost", 1300);
Thread.sleep(3000);
Socket c = new Socket("localhost", 1300);
Thread.sleep(3000);
a.close();
b.close();
c.close();
}
}
Server:
import java.net.ServerSocket;
import java.net.Socket;
public class server {
public static void main(String[] args) throws Exception{
ServerSocket ss = new ServerSocket(1300);
System.err.println("Listening...");
Socket a = ss.accept();
System.err.println("1");
Socket b = ss.accept();
System.err.println("2");
Socket c = ss.accept();
System.err.println("3");
}
}

Categories