I am new to networking and I am trying to write the server client program. Still, I keep getting Address already in use and cant chat. A friend of mine run this in his pc and it was working. Can somebody explain to me why I keep getting this error?
Here is the server class:
import java.net.*;
import java.io.*;
class server
{
public static void main(String []args)
{
try
{
ServerSocket serv = new ServerSocket(8001);
System.out.println("Server up and listening:");
Socket S = serv.accept();
InetAddress obj = S.getInetAddress();
System.out.println("Request coming from:");
BufferedReader br = new BufferedReader(new InputStreamReader(S.getInputStream()));
String msg = br.readLine();
System.out.println("Message recieved:"+msg);
br.close();
serv.close();
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}}
Here is the client class:
import java.net.*;
import java.io.*;
import java.util.*;
class client`{
public static void main(String [] args)
{
Socket s = null;
BufferedOutputStream bout = null;
InetAddress obj = null;
try {
obj = InetAddress.getByName(args[0]);
s = new Socket(obj, 8001);
String str = new Scanner(System.in).nextLine();
byte[] arr = str.getBytes();
bout = new BufferedOutputStream(s.getOutputStream());
bout.write(arr);
bout.flush();
bout.close();
s.close();
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
} }
I appreciate any help you can provide!
use below command to determine if you have any open port on the machine where you are running your Server program
netstat -nao | find "8001"
You can simply change 8001 to another value. It looks like that it is under use by another program. Depends on your operating system, there are plenty ways to learn which ports are occupied.
Related
I have made a Client/Server programme in java, I have gotten it to work using the cmd perfectly as i want, now i am trying to convert the client side of the code into GUI, however i am having trouble with printing the client msg and reading the client input from the text fields and the server msg, here is what I have done so far, i get no errors when compiling but the gui it self doesn't run, any help is appreciated.
Here is the Client code:
import java.net.*;
import java.io.*;
import java.awt.*;
import java.util.Scanner;
import javax.swing.*;
public class TcpClient
{
public static void main(String[] args)
{
try
{
new TcpClient().start();
}
catch(Exception e)
{
System.out.println("Major Error" + e.getMessage());
e.printStackTrace();
}
}
public void start() throws IOException
{
JFrame build = new JFrame("Client");
JTextField serv = new JTextField();
JTextField clie = new JTextField();
build.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
serv.setBounds(50,210,300,50);
build.add(serv);
clie.setBounds(350,210,300,50);
build.add(clie);
//=====================================================================
Socket clientSocket = null;
InetAddress hostA = null;
PrintWriter clientOutput = null;
BufferedReader clientInput = null;
BufferedReader standardInput = null;
try
{
hostA = InetAddress.getLocalHost();
clientSocket = new Socket(hostA.getHostName(), 5600);
clientInput = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
clientOutput = new PrintWriter(clientSocket.getOutputStream(), true);
standardInput = new BufferedReader(new InputStreamReader(System.in));
String serverMsg, clientMsg;
//read from a socket and respond back to server
while((serverMsg = clientInput.readLine()) != null)
{
serv.setText("Server Saying - " + serverMsg);
if(serverMsg.equals("exit"))
break;
clientMsg = standardInput.readLine();
if(clientMsg != null)
{
clie.setText("Client Saying - " + clientMsg);
clientOutput.println(clientMsg);
}
}
}
catch(UnknownHostException e)
{
System.exit(1);
}
catch(IOException e)
{
System.exit(1);
}
finally
{
//clean up time
clientOutput.close();
clientInput.close();
standardInput.close();
clientSocket.close();
}
//=====================================================================
build.setLayout(null);
build.setSize(700,600);
build.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
build.setVisible(true);
build.setResizable(false);
}
}
As mentioned in the comments you should study multithreading and especially the EDT
What is happening right now is that your code and your GUI and preventing each other from working properly. By having your GUI run on the EDT your application can run without holding back the GUI. When the application has changes to report that are relevant for your GUI you can just inform the EDT when the time comes.
Hi there currently i am creating a UDP connection for my program currently its localhost how am i going to insert my IP address so that another computer in the same network will be able to receive the message i type at the server side.
UDPSERVER
package testing;
import java.io.*;
import java.net.*;
public class UdpServer {
public static void main(String args[]) {
String str;
try {
BufferedReader Br;
Br = new BufferedReader(new InputStreamReader(System. in ));
DatagramSocket Sock;
Sock = new DatagramSocket(1000);
DatagramPacket Dp;
System.out.println("Enter the data..... Enter 'exit' to stop");
while (true) {
str = Br.readLine();
Dp = new DatagramPacket(str.getBytes(), str.length(),
InetAddress.getByName("localhost"), 2000);
Sock.send(Dp);
if (str.equals("exit")) break;
}
Sock.close();
} catch (Exception e) {}
}
}
UdpClient
package testing;
import java.net.*;
public class UdpClient {
public static void main(String arg[]) {
String str;
DatagramSocket Sock;
DatagramPacket Dp;
try {
Sock = new DatagramSocket(2000);
byte Buff[] = new byte[1024];
System.out.println("Client ready...");
while (true) {
Dp = new DatagramPacket(Buff, 1024);
Sock.receive(Dp);
str = new String(Dp.getData(), 0, Dp.getLength());
System.out.println(str);
if (str.equals("exit")) break;
}
Sock.close();
} catch (Exception e) {
System.out.println("Connection failure...");
} finally {
System.out.println("Server Disconnected...");
}
}
}
The first step is to try and hardcode the ip of the other computer and test. If that works then look at adding UDP Broadcast Discovery. Here's an example in java:
http://michieldemey.be/blog/network-discovery-using-udp-broadcast/
The idea is that all devices that need to talk broadcast on UDP. Once they hear the broadcast, they need to connect to eachother. Usually one side will need to be pre-determined as the server, and the other as the client.
I'm a beginner (as you can probably tell) and I'm having issues establishing a connection from my very simple client to my very simple server. My server starts up fine as it creates a serversocket that listens on port 43594. However, when I run my client to try to establish a connection, an IOException is thrown by my client as it tries to connect.
I'm doing java in my spare time as a hobby, so I'd really appreciate if someone could help me understand what's going on, where I'm going wrong (or if I'm even going right any where) so as to help me improve.
Here is my Server code:
package src.org;
import java.io.FileInputStream;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.net.*;
import java.io.*;
public class Server {
private static final Logger logger = Logger.getLogger(Server.class.getName());
private final static void createSocket(int portNumber) throws IOException
{
ServerSocket serverSocket = new ServerSocket(portNumber);
Socket clientSocket = serverSocket.accept();
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
}
public static void main(String... args)
{
logger.info("Starting server...");
Properties properties = new Properties();
logger.info("loading settings...");
try
{
properties.load(new FileInputStream("settings.ini"));
Constants.GAME_NAME = properties.getProperty("name");
Constants.PORT = Integer.valueOf(properties.getProperty("port"));
} catch(Exception ex)
{
ex.printStackTrace();
}
logger.info("Creating sockets...");
try
{
logger.info("Socket created. Listening on port: " + Constants.PORT);
createSocket(Constants.PORT);
} catch(Exception ex)
{
logger.log(Level.SEVERE, "Error creating sockets.", ex);
System.exit(1);
}
}
}
Which (to my knowledge) seems to be doing its job.
And here's what I believe to be the culprit class, the client class:
import java.io.*;
import java.net.*;
public class Client {
//private static final String hostName = Constants.HOST_NAME;
//private static final int portNumber = Constants.PORT;
private static final String hostName = "localhost";
private static final int portNumber = 43594;
public static void main(String... args)
{
try (
Socket socket = new Socket(InetAddress.getLocalHost(), portNumber); // using localhost at the moment
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
) {
System.out.println("Client socket created.");
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String fromServer, fromUser;
while((fromServer = in.readLine()) != null)
{
System.out.println("Server:" + fromServer);
fromUser = stdIn.readLine();
if(fromUser != null) {
System.out.println("Client: " + fromUser);
out.println(fromUser);
}
}
} catch(UnknownHostException ex) {
System.err.println("Unknown host: " + hostName);
System.exit(1);
} catch(IOException ioe) {
System.err.println("Couldn't get i/o from: " + hostName);
System.out.println("Error:" + ioe.getMessage());
System.exit(1);
}
}
}
When I ping localhost I get a response; the port on both sides is 43594 and the host is just local. The command line response from the client is:
Client socket created
Couldn't get i/o from: localhost
Error: connection reset
Press any key to continue...
I'm sorry in that I know this would be a very simple fix to many of you, but I can't seem to find an answer or fix it myself. Any insight or help would be greatly appreciated. Cheers.
Sorry if I've left out any other important pieces of information.
You've left out much of the code. The part in the server that sends data on the accepted socket. So the method that calls accept() just exits, the socket is garbage-collected, and closed, and the client keeps doing I/O to the other end of the connection, which is invalid,so you get an exception.
basically what i want to do is develop a chat program(something between an instant messenger and IRC) to improve my java skills.
But I ran into 1 big problem so far: I have no idea how to set up streams properly if there is more than one client. 1:1 chat between the client and the server works easily, but I just don't know what todo so more than 1 client can be with the server in the same chat.
This is what I got, but I doubt its going to be very helpful, since it is just 1 permanent stream to and from the server.
private void connect() throws IOException {
showMessage("Trying to connect \n");
connection = new Socket(InetAddress.getByName(serverIP),27499);
showMessage("connected to "+connection.getInetAddress().getHostName());
}
private void streams() throws IOException{
output = new ObjectOutputStream(connection.getOutputStream());
output.flush();
input = new ObjectInputStream(connection.getInputStream());
showMessage("\n streams working");
}
To read from multiple streams in one program, you're going to have to use multithreading. Because reading from streams is synchronous, you'll need to read from one stream for each thread. See the java tutorial on threads for more info on multithreading.
I've done this several times with ServerSocket(int port) and Socket ServerSocket.accept(). This can be pretty simple by having it listen to the one port you want your chat server client listening on. The main thread will block waiting for the next client to connect, then return the Socket object to that specific client. Usually you'll want to put them in a list to generically handle n-number of clients.
And, yes, you will probably want to make sure each Socket is in a different thread, but that's entirely up to you as the programmer.
Remember, there is no need to re-direct to another port on the server, by virtue of the client using a different source port, the unique 5-tuple (SrcIP, SrcPort, DstIP, DstPort, TCP/UDP/other IP protocol) will allow the one server port to be re-used. Hence why we all use stackoverflow.com port 80.
Happy Coding.
Made something like that a few months back. basically I used a separate ServerSocket and Thread per client server side. When client connects you register that port's input and output streams to a fixed pool and block until input is sent. then you copy the input to each of the other clients and send. here is a basic program run from command line:
Server code:
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
public class ChatServer {
static int PORT_NUMBER = 2012;
public static void main(String[] args) throws IOException {
while (true) {
try (ServerSocket ss = new ServerSocket(PORT_NUMBER)) {
System.out.println("Server waiting #" + ss.getInetAddress());
Socket s = ss.accept();
System.out.println("connection from:" + s.getInetAddress());
new Worker(s).start();
}
}
}
static class Worker extends Thread {
final static ArrayList<PrintStream> os = new ArrayList(10);
Socket clientSocket;
BufferedReader fromClient;
public Worker(Socket clientSocket) throws IOException {
this.clientSocket = clientSocket;
PrintStream toClient=new PrintStream(new BufferedOutputStream(this.clientSocket.getOutputStream()));
toClient.println("connected to server");
os.add(toClient);
fromClient = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));
}
#Override
public void run() {
while (true) {
try {
String message = fromClient.readLine();
synchronized (os) {
for (PrintStream toClient : os) {
toClient.println(message);
toClient.flush();
}
}
} catch (IOException ex) {
//user discnnected
try {
clientSocket.close();
} catch (IOException ex1) {
}
}
}
}
}
}
Client code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
public class Client {
public static void main(String[] args) throws IOException {
final BufferedReader fromUser = new BufferedReader(new InputStreamReader(System.in));
PrintStream toUser = System.out;
BufferedReader fromServer;
final PrintStream toServer;
Socket s = null;
System.out.println("Server IP Address?");
String host;
String port = "";
host = fromUser.readLine();
System.out.println("Server Port Number?");
port = fromUser.readLine();
s = new Socket(host, Integer.valueOf(port));
int read;
char[] buffer = new char[1024];
fromServer = new BufferedReader(new InputStreamReader(s.getInputStream()));
toServer = new PrintStream(s.getOutputStream());
new Thread() {
#Override
public void run() {
while (true) {
try {
toServer.println(">>>" + fromUser.readLine());
toServer.flush();
} catch (IOException ex) {
System.err.println(ex);
}
}
}
}.start();
while (true) {
while ((read = fromServer.read(buffer)) != -1) {
toUser.print(String.valueOf(buffer, 0, read));
}
toUser.flush();
}
}
}
I have Java console app, which i want to control from another computer. I use Socket class to send data through net and pipeline to connect the remote controlled program with Sender and Reader program, as shown:
Reader:
import java.io.*;
import java.net.*;
public class Reader {
//reads information from the remote controlled program
public static void main(String[] args) throws Exception {
Socket s = new Socket(args[0], Integer.parseInt(args[1]));
PrintWriter bw = new PrintWriter(s.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String vstup;
do {
vstup = in.readLine();
if(vstup==null) break;
bw.println(vstup);
} while(true);
s.close();
}
}
Sender:
import java.io.*;
import java.net.*;
public class Sender {
//sends instruction to the remote controlled program
public static void main(String[] args) throws Exception {
Socket s = new Socket(args[0], Integer.parseInt(args[1]));
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
String vstup;
do {
vstup = in.readLine();
if(vstup==null) break;
System.out.println(vstup);
} while(true);
s.close();
}
}
RemoteController:
import java.net.*;
import java.io.*;
public class RemoteController {
public static void main(String[] main) throws IOException {
ServerSocket ss = new ServerSocket(Integer.parseInt(main[0]));
System.out.println("Done, please connect the program.");
Socket reader = ss.accept(); //reads what the program says
System.out.println("reader connected");
Socket writer = ss.accept(); //writes into the program
System.out.println("writer connected");
BufferedReader read = new BufferedReader(new InputStreamReader(reader.getInputStream()));
PrintWriter write = new PrintWriter(writer.getOutputStream(), true);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
for(int i = 0; i<5; i++) {
write.println(br.readLine());
System.out.println(read.readLine());
}
write.close();
read.close();
writer.close();
reader.close();
ss.close();
}
}
now i run the Remote controller and then i write
java Sender localhost 1234 | java SomeProgram | java Reader localhost 1234
into a comand prompt to test whenever it works. It sometimes works, sometimes not, any advise how to make it work everytime?
All the problem was that the Sender and Reader programms conected in a random order to the main program, so adding Thread.sleep(200) resolved my problem, sorry for annoying.
PS: If you program in java (and cmd), try it, iƄ really fun i think.