What do I change my socket to? - java

alI created a simple text based RPG and after alot of work managed to put it on a website (www.worldofthedrakon.com). I just created a server and client but I am having problems with users accessing the server from their computer. I have my socket set up as:
Socket socket = new Socket("localhost", 8800);
Now i have tested changing localhost out for my IP, to no avail. The errors I'm getting are connection timed out, and connection refused. Could someone point me in the right direction? I apologize if my problem seems vague, more code can be provided. Theres alot of it so I didnt want to bombard you :) Thank you.
ServerSide:
public Server() {
setLayout(new BorderLayout());
add(new JScrollPane(jta), BorderLayout.CENTER);
setTitle("Multi-Thread Server");
setSize(500, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
try {
ServerSocket serverSocket = new ServerSocket(8800);
jta.append("MultiThreadServer started at " + new Date() + '\n');
int clientNo = 1;
while(true) {
Socket socket = serverSocket.accept();
jta.append("Server Thread for client " + clientNo + " at " + new Date() + '\n');
InetAddress inetAdress = socket.getInetAddress();
jta.append("Client " + clientNo + "'s host name is " + inetAdress.getHostName() + "\n");
jta.append("Client " + clientNo + "'s IP Address is " + inetAdress.getHostAddress() + "\n");
HandleAClient task = new HandleAClient(socket);
new Thread(task).start();
clientNo++;
}
} catch(IOException ex) {
System.err.println(ex);
}
Client Side:
try {
Socket socket = new Socket("localhost", 8800);
fromServer = new DataInputStream(socket.getInputStream());
toServer = new DataOutputStream(socket.getOutputStream());
} catch (IOException ex) {
jta_TextArea.setText(ex.toString() + '\n');
}

Your socket is bound to localhost this means in can only serve the local client. If you want others to see your server the first step is to bind to the IP address that is visible to those others!

I think you want to be using a ServerSocket and not a regular socket.

"localhost" is exactly that; it is your local host or your machine. If you are trying to connect your socket to some other host (like whatever resolves to www.worldofthedrakon.com), you need to get that hostname or its IP address in there.
Socket socket = new Socket("worldofthedrakon.com", 8800);
Then you get to fight the firewall issues. Connection Refused is usually an indication that there is a firewall or two in the way. Do you know that port 8800 is open on your new host?

Related

Java Socket Client Unable to Connect to C# Socket Server

I have a use case, where I have to send data from a .NET application, to a Java application and I'm trying to do this using sockets. I have a server created using C# -
TcpListener tcpListener = null;
IPAddress ipAddress = Dns.GetHostEntry("localhost").AddressList[0];
try
{
// Set the listener on the local IP address
// and specify the port.
tcpListener = new TcpListener(ipAddress, 13);
tcpListener.Start();
Console.WriteLine("The server is running at port 13...");
Console.WriteLine("The local End point is -" +
tcpListener.LocalEndpoint);
output = "Waiting for a connection...";
Console.WriteLine(output);
Socket s = tcpListener.AcceptSocket();
Console.WriteLine("Connection accepted from " + s.RemoteEndPoint);
}
catch (Exception e)
{
output = "Error: " + e.ToString();
Console.WriteLine(output);
}
}
On the Java side, I have created a socket which listens to the same host and port -
Socket socket;
try {
socket = new Socket( "localhost", 13);
System.out.println("Connection established");
BufferedReader input =
new BufferedReader(new InputStreamReader(socket.getInputStream()));
String answer = input.readLine();
System.out.println(answer);
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
I'm getting the below error - java.net.ConnectException: Connection refused: connect. I have used telnet localhost 13, to check if my server is really running, and it is. So i don't think it could be an issue with server not running or firewalls, since both are running locally. Any ideas on how to resolve this?
I tried your code and I had exactly the same problem. Your C# TCP Server only binds to the IPv6 interface (check e.g. the resource monitor listening addresses). If you change your server to new TcpListener(IPAddress.Any, 13) it should work.

How to send authentication string to establish TCP connection? [duplicate]

This question already has an answer here:
java.net.ConnectException: Connection refused TCP
(1 answer)
Closed 6 years ago.
I have to establish a TCP connection to a server, which requires that I send the credential to logon in the format:
<STX>username=fred&password=123456<ETX>
Let's say host: qstage.thetcphost.com and port:8999
I am new to socket programming and using the same to implement this. I have used java.net.Socket at the client side but I dont know how do I send the above string for authentication to the TCP Server in Java.
I am able to telnet the server now.
But how do I pass the credential string in the < STX >...< ETX > format after (or during):
Socket socket = new Socket("mshxml.morningstar.com", 8999);
I mean what is the piece of code that I have to write to authenticate myself to the TCP server?
I have searched this site for this info but could not find any.
Help would be greatly appreciated.
Establish the socket connection is the first step before you can send any creds information.
If this step is failing, consider the specs from your target server. Is the correct port provided? Any consideration on protocol?
Usually, the authentication will be happen after you have already established successfully the connection.
Editted: Add source code for writing to socket from a socket client.
Now, in this context, you're a socket client, try to send creds to server.
public class GreetingClient
{
public static void main(String [] args)
{
String serverName = args[0];
int port = Integer.parseInt(args[1]);
try
{
System.out.println("Connecting to " + serverName +
" on port " + port);
Socket client = new Socket(serverName, port);
System.out.println("Just connected to "
+ client.getRemoteSocketAddress());
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)
{
e.printStackTrace();
}
}
}
Sample found here: http://www.tutorialspoint.com/java/java_networking.htm

Java UDP Client Not Receiving Packets

I've made a java application which uses UDP and I can't seem to receive packets outside LAN when hosting on my computer. I tried putting my application on a Hosted Server and it seemed to work (receives packet).
What is causing this to happen? I want it to work on my computer as well.
CLIENT:
try {
this.socket = new DatagramSocket(2500);
} catch (SocketException e1) {
System.out.println("Could not establish connection");
return;
}
while(true){
byte[] data = new byte[1024];
DatagramPacket packet = new DatagramPacket(data, data.length);
try{
socket.receive(packet);
}catch(IOException e){
System.out.println("Connection close");
break;
}
System.out.println("RECEIVED " + new String(packet.getData()));
}
SERVER:
try {
this.socket = new DatagramSocket(25860);
} catch (SocketException e) {
e.printStackTrace();
}
try {
byte[] data = datas.getBytes();
DatagramPacket packet = new DatagramPacket(data, data.length, ipAddress, 2500);
socket.send(packet);
}catch(IOException e) {
}
System.out.println("Sent " + ipAddress.getHostAddress() + ":" + port + " " + new String(datas));
IP Address is correct, it exactly prints out the same IP as my CLIENT. However I'm still not receiving.
If it works in one computer (single) and not on the other try checking the firewall, UDP connections should be allowed in your computer.

Java UDP Port 161 scan

Port 161 is used by SNMP. I wrote a small peice of code to check if a device is running SNMP on this port.
public boolean isPortOpen(String ip, int port, int timeout) {
try {
Socket socket = new Socket();
socket.connect(new InetSocketAddress(ip, port), timeout);
socket.close();
logger.info(threadId, "Port is Open : " + ip + ":" + port );
return true;
} catch (IOException ex) {
logger.error(threadId, "isPortOpen : " + ip + ":" + port + "\t"+ ex.getMessage());
return false;
}
}
However to my surprise the code always returns false for port 161 even though the box is running SNMP and other tools such as PortQryV2 return true for port 161. Can someone please help!! TIA

Java Broadcasting and listening on same port

How can broadcast a message from single server to multiple clients and listen for a reply from one of the clients.
I used Multicast Programming to broadcast the message to the clients. And If i send the message from one of my clients back to the server either through TCP or UDP, I am getting a "java.net.ConnectException: Connection refused: connect" exception.
Please help me out.
Thanks in Advance.
Sender Code :
// Broadcasting the message
msg = "This is multicast! " + counter;
counter++;
outBuf = msg.getBytes();
// Send to multicast IP address and port
InetAddress address = InetAddress.getByName("224.2.2.3");
outPacket = new DatagramPacket(outBuf, outBuf.length, address,
PORT);
socket.send(outPacket);
System.out.println("Server sends : " + msg);
socket.close();
// Receiving TCP
apSock = new Socket("131.151.88.165", 6161);
apBuffReader = new BufferedReader(new InputStreamReader(
apSock.getInputStream()));
while ((ap2Toap1 = apBuffReader.readLine()) != null) {
System.out.println(ap2Toap1);
}
Receiver Code :
count++;
inPacket = new DatagramPacket(inBuf, inBuf.length);
socket.receive(inPacket);
String msg = new String(inBuf, 0, inPacket.getLength());
System.out.println("From " + inPacket.getAddress() + " Msg : "
+ msg);
socket.close();
// Sending TCP
apSock = new Socket("131.151.88.165", 6161);
System.out.println("Hello2");
respWriter = new PrintWriter(apSock.getOutputStream());
System.out.println("Writing back to the server");
respWriter.println(outBuf);
if (respWriter != null)
respWriter.close();
There is no listening in your code. TCP listening in Java is accomplished via a ServerSocket. You aren't using one. Instead you're using Sockets at both ends. So what you have is two clients and no server. No communication is possible between two TCP clients.

Categories

Resources