muilti threading in java [duplicate] - java

This question already has an answer here:
Java server multithreading [closed]
(1 answer)
Closed 9 years ago.
so what i am trying to do is write a server and a client. the server should listen for a connection and service that connection on a differ thread and keep listening for more client. once connected the client will send over the IP it wished the server to resolve. the server sould write this back the the client. this is what i got so far... how do i make the server better. and how to write the client
How do you write the client file to connect to this and send it the ip they want.
import java.io.IOException;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Server implements Runnable {
Socket csocket;
Server(Socket csocket) {
this.csocket = csocket;
}
public static void main(String args[])
throws Exception {
ServerSocket ssock = new ServerSocket(6053);
System.out.println("Listening");
while (true) {
Socket sock = ssock.accept();
System.out.println("Connected");
new Thread(new Server(sock)).start();
}
}
public void run() {
try {
PrintStream pstream = new PrintStream
(csocket.getOutputStream());
pstream.close();
csocket.close();
}
catch (IOException e) {
System.out.println(e);
}
}
}

what you can do is make it for "user friendly", i have done this thing before and made a successful IM program.
ideas:
make it able to get global IP
display a handshake (if connected = true){ system.out.print( has connected!);}

Related

Socket connection not workin in flutter release apk

I am new to working with sockets, and I am working on this project where a connection between my android flutter app and a java server is needed, to do this I am trying socket programming.
The server code is fairly simple, I create a new thread for every client connected and I give them a bunch of URLs, later on, this should be replaced by a query result. here is the java code:
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class CrawlitServer {
// The port number on which the server will listen for incoming connections.
public static final int PORT = 6666;
//main method
public static void main(String[] args) {
System.out.println("The server started .. ");
// Create a new server socket
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(PORT);
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
// Listen for incoming connections and create a new thread for each one
while (true) {
try {
new CrawlitServerThread(serverSocket.accept()).start();
}
catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}
public static class CrawlitServerThread extends Thread {
private final Socket socket;
public CrawlitServerThread(Socket socket) {
this.socket = socket;
}
public void run() {
List<String> list = new ArrayList<>();
//assign a value to list
list.add("http://www.google.com");
list.add("http://www.yahoo.com");
list.add("http://www.bing.com");
list.add("http://www.facebook.com");
list.add("http://www.twitter.com");
list.add("http://www.linkedin.com");
list.add("http://www.youtube.com");
list.add("http://www.wikipedia.com");
list.add("http://www.amazon.com");
list.add("http://www.ebay.com");
list.add("http://stackoverflow.com");
list.add("http://github.com");
list.add("http://quora.com");
list.add("http://reddit.com");
list.add("http://wikipedia.org");
try {
// Get the input stream from the socket
DataInputStream inputStream = new DataInputStream(socket.getInputStream());
Scanner scanner = new Scanner(inputStream);
DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream());
PrintWriter writer = new PrintWriter(outputStream, true);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println("Received Message from client: " + line);
writer.println(list + "\n");
}
}
catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}
}
Now I run this server and connect to it using sockets in Flutter, I give it the IP address I get from the ipconfig command, and here is the dart code:
import 'dart:async';
import 'dart:io';
//Utilities that manage connections with server sockets.
//ServerUtil Class
class ServerUtil {
static const port = 6666;
static const host = MY_IP_GOES_HERE;
static late Socket socket;
static bool connected = false;
//a list of urls returned by the server
static List<String> urls = [];
//Constructor
ServerUtil() {
//Initialize the socket.
Socket.connect(host, port).then((Socket sock) {
socket = sock;
connected = true;
socket.listen(dataHandler,
onError: errorHandler, onDone: doneHandler, cancelOnError: false);
//send a message to the server.
}).catchError((e) {
print("Unable to connect: $e");
});
}
//Query method that sends a message to the server. The server will return a list of urls.
//The urls will be added to the urls list.
//The urls list will be returned.
static Future<List<String>> query(String userQuery) async {
urls.clear();
//check if socket is connected.
if (connected) {
//send the query to the server.
socket.writeln(userQuery);
await Future.delayed(const Duration(milliseconds: 200));
print(urls);
return urls;
}
//if socket is not connected, wait for 5 seconds and try again.
await Future.delayed(const Duration(milliseconds: 50));
return query(userQuery);
}
//Handles data from the server.
void dataHandler(data) {
//String of received data.
String dataString = String.fromCharCodes(data).trim();
//remove first and last character from the string.
dataString = dataString.substring(1, dataString.length - 1);
//remove all the whitespace characters from the string.
dataString = dataString.replaceAll(RegExp(r'\s+'), '');
urls = dataString.split(',');
}
//Handles errors from the server.
void errorHandler(error, StackTrace trace) {
print(error);
}
//Handles when the connection is done.
void doneHandler() {
socket.destroy();
}
}
This works perfectly fine while using a debug apk running it on my real Note 9 device. The problem however is that when I build a release apk and try it out, nothing happens.
The way I set it up is that I wait for the query method in an async and then I send the result to a new screen and push that screen into the navigator.
But in the release apk nothing happens, the new screen doesn't load.
So this leads me to my first question:
Is there a way to debug a release apk? see what exceptions it throws or print some stuff to console?
I have the server running on my Laptop, and the app runs on my phone which is on the same WIFI network.
My second question is:
Do I need to enable some sort of option with my router or my laptop to allow my phone to connect? it does connect in debug mode without any modifications
I tried some random things, like using 'localhost' instead of my IP, as I would normally connect say with a java client for example, but it didn't work.
My last question is:
Does the release apk or like android OS prevent connections to local hosts, maybe because it thinks it is not secure? but then it still connects in debug mode.
Thank you for your time.

JAVA:java.net.BindException: Address already in use: JVM_Bind [duplicate]

This question already has answers here:
How do I resolve the "java.net.BindException: Address already in use: JVM_Bind" error?
(22 answers)
Closed 5 years ago.
I've wrote these two classes, one for client and the other for server. When I run both of them I get the following error:
java.net.BindException: Address already in use: JVM_Bind...
What is the problem? Also I use TCPview software and there were just two java.exe that use the same port. These two java.exe processes belong to the apps.
Here is the code:
Server Code
/**
*
* #author casinoroyal
*/
public class server {
public static ServerSocket socket1;
public static void main(String[] args) {
try {
socket1 = new ServerSocket(1254);
String request="";
Socket mylink=socket1.accept();
System.out.println("server feels=====");
DataInputStream input= new DataInputStream(mylink.getInputStream());
DataOutputStream output=new DataOutputStream(mylink.getOutputStream());
Scanner chat=new Scanner(System.in);
while(!request.equals("QUIT")){
request=input.readUTF();
output.writeUTF(chat.next());
}
socket1.close();
} catch (IOException ex) {
System.out.println(ex);
}
}
}
Client Code
package javaapplication9;
import java.net.*;
import java.io.*;
import java.util.*;
public class client {
//main
public static void main(String[] args) {
System.out.println("client want to be connected");
try {
Socket mysock = new Socket(InetAddress.getLocalHost(),1254);
System.out.println("client has been connected");
DataInputStream input = new DataInputStream(mysock.getInputStream());
DataOutputStream output = new DataOutputStream(mysock.getOutputStream());
String reque="";
Scanner scan1=new Scanner(System.in);
String sendmsg=scan1.next();
while(!reque.equals("QUIT")){
output.writeUTF (sendmsg);
reque=input.readUTF();
}
mysock.close();
} catch (IOException ex) {
System.out.println("client rejected"+ex);
}
}
}
What is the problem? Also I use TCPview software and there were just two java.exe that use the same port. These two java.exe processes belong to the apps.
Here is your problem.
You tried to bind 2 sockets at the same port of your computer, and you can't bind 2 sockets at the same port on the same computer.
It's probably because you had an existing process that is listening at the port 1254 ( probably an instance of your server app ), and you tried to run your server app which tried to bind also at the port 1254

How to connect 2 different computers on a network using a chat application in Java?

I have a simple pair of client and server programs. Client connects to server and when it does connect, the server replies with a "Hello there" message. How should I modify the program if I want the client and server programs to run on different systems?
Here is the code for the client side..
package practice;
import java.io.*;
import java.net.*;
public class DailyAdviceClient
{
public static void main(String args[])
{
DailyAdviceClient dac = new DailyAdviceClient();
dac.go();
}
public void go()
{
try
{
Socket incoming = new Socket("127.0.0.1",4242);
InputStreamReader stream = new InputStreamReader(incoming.getInputStream());
BufferedReader reader = new BufferedReader(stream);
String advice = reader.readLine();
reader.close();
System.out.println("Today's advice is "+advice);
}
catch(Exception e)
{
System.out.println("Client Side Error");
}
}
}
and here is the code for the server
package practice;
import java.io.*;
import java.net.*;
public class DailyAdviceServer
{
public static void main(String args[])
{
DailyAdviceServer das = new DailyAdviceServer();
das.go();
}
public void go()
{
try
{
ServerSocket serversock = new ServerSocket(4242);
while(true)
{
Socket outgoing = serversock.accept();
PrintWriter writer = new PrintWriter(outgoing.getOutputStream());
writer.println("Hello there");
writer.close();
}
}
catch(Exception e)
{
System.out.println("Server Side Problem");
}
}
}
just change "127.0.0.1" on the client with the server's IP and make sure the port 4242 is open.
Socket incoming = new Socket("127.0.0.1",4242);
This is creating a socket listening to the server at the address 127.0.0.1 on port 4242. If you change the server to another address, for example of a different pc, then change the ip address that your socket is listening to.
It is also worth noting that you will probably have to open up or allow access to the ports you are using.
Client requires ip address and port of server, means ip of that system which you making server and port (4242).so in client you need to change
Socket incoming = new Socket("127.0.0.1",4242); BY
Socket incoming = new Socket("IP address of server",4242);
And make sure both system is connected via wired or wireless network.

Is it possible to run a socket server and socket client on the same machine?

In java it is possible to create a socket server and a socket client, is it possible to have an instance of the socket server running and a socket/server client that is receiving data from the socket server on the same machine?
e.g the socket server runs on port 60010
and the socket client is running on the same machine connecting to that port through a socket or will I need to by a new machine and add it to my network? If it has a unique IP Address and port number running on the TCP/IP layer.
Here's a simple runnable example to get you started. It starts two threads, one with a ServerSocket and one which makes a Socket connection. One continuously sends strings and the other prints them.
You should simply be able to run this class as-is.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
public class SocketTest {
public static void main(String[] args) throws IOException {
startServer();
startSender();
}
public static void startSender() {
(new Thread() {
#Override
public void run() {
try {
Socket s = new Socket("localhost", 60010);
BufferedWriter out = new BufferedWriter(
new OutputStreamWriter(s.getOutputStream()));
while (true) {
out.write("Hello World!");
out.newLine();
out.flush();
Thread.sleep(200);
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
public static void startServer() {
(new Thread() {
#Override
public void run() {
ServerSocket ss;
try {
ss = new ServerSocket(60010);
Socket s = ss.accept();
BufferedReader in = new BufferedReader(
new InputStreamReader(s.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
}
Yes, you can have the following on the same machine:
ServerSocket server = new ServerSocket(60010);
Socket client = server.accept();
Somewhere else:
Socket socket = new Socket("localhost", 60010);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
out.println("Hello server");
Yes, you can run a client and server on the same machine. I do it all the time for development. If you are having troubles though, some routers have problems forwarding packets back to themselves. Try using localhost instead of your external IP for development.
Yes it is completely possible. Every OS has a loopback interface. You can have multiple clients connect to one server on your computer. This kind of communication takes place over the loopback interface.

close all the sockets after using it? on server side

Do I have to close all the sockets after using it? Where should I put them in this code? My program just works normally when I run it. However, when I re-run it, it said "Exception in thread "main" java.net.BindException: Address already in use: JVM_Bind". Therefore, I think I did not close all the socket after using it.
import java.io.*;
import java.net.*;
import java.util.*;
public class Server2 {
public static void main(String args[]) throws Exception {
int PORT = 5555; // Open port 5555
//open socket to listen
ServerSocket server = new ServerSocket(PORT);
Socket client = null;
while (true) {
System.out.println("Waiting for client...");
// open client socket to accept connection
client = server.accept();
System.out.println(client.getInetAddress()+" contacted ");
System.out.println("Creating thread to serve request");
ServerStudentThread student = new ServerStudentThread(client);
student.start();
}
}
}
Call server.close() in a finally block.
ServerSocket server = new ServerSocket(PORT);
try {
while (true) {
System.out.println("Waiting for client...");
// open client socket to accept connection
Socket client = server.accept();
System.out.println(client.getInetAddress()+" contacted ");
System.out.println("Creating thread to serve request");
ServerStudentThread student = new ServerStudentThread(client);
student.start();
}
} finally {
server.close();
}
Address already in use: JVM_Bind - means, that you operation system is not closed socket after previous use. It closes on timeout about 30-180 seconds.
I don't realy know how to do this in java, but in C code it may be done like this, before bind system function call:
int yes = 1;
setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int));
That mean: set the flag (option) SO_REUSEADDR to sockfd socket.
In java must exists appropriate mechanism for do the same.
You are running an infinite while loop , have a boolean variable to say when to stop , i think you are not exiting gracefully, that is why port is not closed.
May be you can try like this
import java.io.*;
import java.net.*;
import java.util.*;
public class Server2 {
static int NUM_CONN_TO_WAIT_FOR=15;
boolean exitServer =false;
public static void main(String args[]) throws Exception {
int PORT = 5555; // Open port 5555
//open socket to listen
ServerSocket server = new ServerSocket(PORT);
Socket client = null;
static int connections =0;
try
{
while (!exitServer ) {
System.out.println("Waiting for client...");
// open client socket to accept connection
if ( connections < NUM_CONN_TO_WAIT_FOR )
{
client = server.accept();
System.out.println(client.getInetAddress()+" contacted ");
System.out.println("Creating thread to serve request");
ServerStudentThread student = new ServerStudentThread(client);
student.start();
} else
{
exitServer =true;
}
connections++;
}
} catch (Exception e)
{
System.out.println(e.printStackTrace());
}
finally
{
if ( client != null)
client.close();
if ( server!= null)
server.close();
}
}
}

Categories