How can i create network streams in java android? - java

Is there a way I could create an array of network streams in java. C# supports creation of an array of Network Streams.
AFAIK we need to create separate InputStreams and OutputStreams in order to receive and send data in Java.
What I want to do is to make a number of TCP connections to send and receive data.
Is there a work around in java for this?

You can achieve that by creating multiple instances of Socket as follows:
Server.java
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 Server
{
private static int CLIENT_COUNT = 0;
public static void main(String[] args) throws IOException
{
ServerSocket ss = new ServerSocket(2000);
while(true)
{
Socket s = ss.accept();
new SocketHandler("Handler#" + ++CLIENT_COUNT, s).start();
}
}
}
class SocketHandler extends Thread
{
private PrintWriter pw;
private BufferedReader br;
public SocketHandler(String name, Socket socket) throws IOException
{
super(name);
this.pw = new PrintWriter(socket.getOutputStream(), true);
this.br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
}
#Override
public void run()
{
String message;
try
{
while((message = br.readLine()) != null)
{
System.out.println("Server#" + getName() + " - Client sent: " + message);
sendMessage("Server#" + getName() + ": echo " + message);
}
}
catch(IOException e)
{
e.printStackTrace();
System.out.println("Server#" + getName() + " -> IOException");
}
}
public void sendMessage(String message)
{
pw.println(message);
System.out.println("Server#" + getName() + " is sending ~ " + message);
}
}
Client.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client
{
private static int SOCKET_COUNT = 0;
public static void main(String[] args) throws UnknownHostException, IOException
{
Socket s1 = new Socket(InetAddress.getLocalHost(), 2000);
Socket s2 = new Socket(InetAddress.getLocalHost(), 2000);
Socket s3 = new Socket(InetAddress.getLocalHost(), 2000);
Socket s4 = new Socket(InetAddress.getLocalHost(), 2000);
LocalSocketHandler h1 = new LocalSocketHandler("LocalHandler#" + ++SOCKET_COUNT, s1);
LocalSocketHandler h2 = new LocalSocketHandler("LocalHandler#" + ++SOCKET_COUNT, s2);
LocalSocketHandler h3 = new LocalSocketHandler("LocalHandler#" + ++SOCKET_COUNT, s3);
LocalSocketHandler h4 = new LocalSocketHandler("LocalHandler#" + ++SOCKET_COUNT, s4);
h1.start();
h2.start();
h3.start();
h4.start();
h1.sendMessage("I am socket #1!");
h2.sendMessage("I am socket #2!");
h3.sendMessage("I am socket #3!");
h4.sendMessage("I am socket #4!");
}
}
class LocalSocketHandler extends Thread
{
private PrintWriter pw;
private BufferedReader br;
public LocalSocketHandler(String name, Socket socket) throws IOException
{
super(name);
this.pw = new PrintWriter(socket.getOutputStream(), true);
this.br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
}
#Override
public void run()
{
String message;
try
{
while((message = br.readLine()) != null)
{
System.out.println("Client#" + getName() + " - Server sent: " + message);
}
}
catch(IOException e)
{
e.printStackTrace();
System.out.println("Client#" + getName() + " -> IOException");
}
}
public void sendMessage(String message)
{
pw.println(message);
System.out.println("Client#" + getName() + " is sending ~ " + message);
}
}
Client's console:
Client#LocalHandler#1 is sending ~ I am socket #1!
Client#LocalHandler#2 is sending ~ I am socket #2!
Client#LocalHandler#3 is sending ~ I am socket #3!
Client#LocalHandler#4 is sending ~ I am socket #4!
Client#LocalHandler#1 - Server sent: Server#Handler#1: echo I am socket #1!
Client#LocalHandler#3 - Server sent: Server#Handler#3: echo I am socket #3!
Client#LocalHandler#2 - Server sent: Server#Handler#2: echo I am socket #2!
Client#LocalHandler#4 - Server sent: Server#Handler#4: echo I am socket #4!
Server's console:
Server#Handler#1 - Client sent: I am socket #1!
Server#Handler#1 is sending ~ Server#Handler#1: echo I am socket #1!
Server#Handler#3 - Client sent: I am socket #3!
Server#Handler#3 is sending ~ Server#Handler#3: echo I am socket #3!
Server#Handler#2 - Client sent: I am socket #2!
Server#Handler#2 is sending ~ Server#Handler#2: echo I am socket #2!
Server#Handler#4 - Client sent: I am socket #4!
Server#Handler#4 is sending ~ Server#Handler#4: echo I am socket #4!

Related

Toggle between two network ports Java

I am trying to send a message from publisher file (sending on port 8000) which is received by Server (listening on port 5000 and 8000)and which forwards the message to the subscriber(listening on port 5000). The problem is that, communication between publisher and server is fine, however, I am not able to forward the message to the subscriber because the server is still listening to publisher and toggling to the subscriber port and forwarding the message. Any suggestion is appretiated
Publisher
package serverclient;
import java.net.*;
import java.io.*;
public class Publisher {
public static void main (String [] args) throws IOException{
Socket sock = new Socket("127.0.0.1",8000);
// reading from keyboard (keyRead object)
BufferedReader keyRead = new BufferedReader(new InputStreamReader(System.in));
// sending to client (pwrite object)
OutputStream ostream = sock.getOutputStream();
PrintWriter pwrite = new PrintWriter(ostream, true);
InputStream istream = sock.getInputStream();
BufferedReader receiveRead = new BufferedReader(new InputStreamReader(istream));
System.out.println("Start the chitchat, type and press Enter key");
String receiveMessage,sendMessage;
while(true)
{
sendMessage = keyRead.readLine(); // keyboard reading
pwrite.println(sendMessage); // sending to server
pwrite.flush(); // flush the data
if((receiveMessage = receiveRead.readLine()) != null) //receive from server
{
System.out.println(receiveMessage); // displaying at DOS prompt
}
else{
System.out.print("Null");
}
}
}
}
Subscriber
package serverclient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
public class Subscriber {
public static void main (String [] args) throws IOException{
Socket sock = new Socket("127.0.0.1",5000);
// receiving from server ( receiveRead object)
InputStream istream = sock.getInputStream();
BufferedReader receiveRead = new BufferedReader(new InputStreamReader(istream));
System.out.println("Recive side");
System.out.print("Connection Status: " + sock.isConnected() + " " + sock.getPort());
String receiveMessage, sendMessage;
while(true)
{
System.out.print("Hey man " + receiveRead.readLine() + "\n");
if((receiveMessage = receiveRead.readLine()) != null) //receive from server
{
System.out.println(receiveMessage); // displaying at DOS prompt
break;
}
else{
System.out.print("Null");
}
}
}
}
Server
package serverclient;
import java.io.*;
import java.net.*;
public class Server extends Thread{
private Socket socket;
private int clientNumber;
public Server(Socket socket, int clientNumber){
this.socket = socket;
this.clientNumber = clientNumber;
if(socket.getLocalPort() == 5000)System.out.print("\nSubscriber "+ clientNumber +" is connected to the server");
if(socket.getLocalPort() == 8000)System.out.print("\nPublisher "+ clientNumber +" is connected to the server");
}
#Override
public void run(){
try {
BufferedReader dStream = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
System.out.print("\nSocket Address "+ socket.getLocalPort() + " " + socket.getPort());
while(true){
if ( socket.getInputStream().available() != 0 && socket.getLocalPort() == 8000 ){
synchronized(this){
String clMessage = dStream.readLine();
System.out.println(clMessage);
out.println("Hey the publisher has sent the message : " + clMessage);
}
}else if (socket.getInputStream().available() != 0 && socket.getLocalPort() == 5000 ){
out.println("Hey man I am so good");
}
}
} catch (IOException ex) {
System.out.print("\nError has been handled 1\n");
}finally{
try {
socket.close();
} catch (IOException ex) {
System.out.print("\nError has been handled 2\n");
}
}
}
public static void main(String [] args) throws IOException{
int subNumber = 0;
int pubNumber = 0;
ServerSocket servSockpub = new ServerSocket(8000);
ServerSocket servSocksub = new ServerSocket(5000);
try {
while (true) {
Server servpub = new Server(servSockpub.accept(),++pubNumber);
servpub.start();
System.out.print("\nThe server is running on listen port "+ servSockpub.getLocalPort());
Server servsub = new Server(servSocksub.accept(),++subNumber);
servsub.start();
System.out.print("\nThe server is running on listen port "+ servSocksub.getLocalPort());
}
} finally {
servSockpub.close();
servSocksub.close();
}
}
}
I see nothing wrong with the server ports (no duplicates/collisions).
But you have no code whatsoever that bridges data between the 2 sockets.
Basically, you should have 1 server that receives the 2 sockets and move data across in1-out2.
Careful too, in your code you can only connect a subscriber once the publisher has connected.

Multi Client Simple Chat(non-GUI) Server in Java using threads

I am unable to figure out how to stop the message from appearing twice on both the client's screen.
The Actual output should be something like this:
Steps for Running the code:
1. Run Server on one terminal
2. Run two clients on two different terminals
When I run the Server - main method creates a Server object:
public static void main(String[] args) throws IOException {
Server server = new Server();
}
Server Constructor:
Server() throws IOException {
Date dNow = new Date();
System.out.println("MultiThreadServer started at " + String.format("%tc", dNow));
System.out.println();
ServerSocket server = new ServerSocket(8000);
ClientSockets = new Vector<Socket>();
while (true) {
Socket client = server.accept();
AcceptClient acceptClient = new AcceptClient(client);
System.out.println("Connection from Socket " + "[addr = " + client.getLocalAddress() + ",port = "
+ client.getPort() + ",localport = " + client.getLocalPort() + "] at "
+ String.format("%tc", dNow));
System.out.println();
//System.out.println(clientCount);
}
//server.close();
}
I am using Socket to connect to the server. Here is my Server code.
Server.java
import java.io.IOException;
import java.net.*;
import java.util.Vector;
import java.io.*;
import java.util.*;
import java.io.DataInputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.time.LocalDateTime;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.text.*;
import java.util.Scanner;
public class Server {
static Vector<Socket> ClientSockets;
int clientCount = 0;
//int i = 0;
Server() throws IOException {
Date dNow = new Date();
System.out.println("MultiThreadServer started at " + String.format("%tc", dNow));
System.out.println();
ServerSocket server = new ServerSocket(8000);
ClientSockets = new Vector<Socket>();
while (true) {
Socket client = server.accept();
AcceptClient acceptClient = new AcceptClient(client);
System.out.println("Connection from Socket " + "[addr = " + client.getLocalAddress() + ",port = "
+ client.getPort() + ",localport = " + client.getLocalPort() + "] at "
+ String.format("%tc", dNow));
System.out.println();
//System.out.println(clientCount);
}
//server.close();
}
public static void main(String[] args) throws IOException {
Server server = new Server();
}
class AcceptClient extends Thread {
Socket ClientSocket;
DataInputStream din;
DataOutputStream dout;
AcceptClient(Socket client) throws IOException {
ClientSocket = client;
din = new DataInputStream(ClientSocket.getInputStream());
dout = new DataOutputStream(ClientSocket.getOutputStream());
//String LoginName = din.readUTF();
//i = clientCount;
clientCount++;
ClientSockets.add(ClientSocket);
//System.out.println(ClientSockets.elementAt(i));
//System.out.println(ClientSockets.elementAt(1));
start();
}
public void run() {
try {
while (true) {
String msgFromClient = din.readUTF();
System.out.println(msgFromClient);
for (int i = 0; i < ClientSockets.size(); i++) {
Socket pSocket = (Socket) ClientSockets.elementAt(i);
DataOutputStream pOut = new DataOutputStream(pSocket.getOutputStream());
pOut.writeUTF(msgFromClient);
pOut.flush();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Client.java
import java.net.Socket;
import java.util.Scanner;
import java.io.*;
import java.net.*;
public class Client implements Runnable{
Socket socketConnection;
DataOutputStream outToServer;
DataInputStream din;
Client() throws UnknownHostException, IOException {
socketConnection = new Socket("127.0.0.1", 8000);
outToServer = new DataOutputStream(socketConnection.getOutputStream());
din = new DataInputStream(socketConnection.getInputStream());
Thread thread;
thread = new Thread(this);
thread.start();
BufferedReader br = null;
String ClientName = null;
Scanner input = new Scanner(System.in);
String SQL = "";
try {
System.out.print("Enter you name: ");
ClientName = input.next();
ClientName += ": ";
//QUERY PASSING
br = new BufferedReader(new InputStreamReader(System.in));
while (!SQL.equalsIgnoreCase("exit")) {
System.out.println();
System.out.print(ClientName);
SQL = br.readLine();
//SQL = input.next();
outToServer.writeUTF(ClientName + SQL);
//outToServer.flush();
//System.out.println(din.readUTF());
}
} catch (Exception e) {
System.out.println(e);
}
}
public static void main(String[] arg) throws UnknownHostException, IOException {
Client client = new Client();
}
public void run() {
while (true) {
try {
System.out.println("\n" + din.readUTF());
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
The reason you have this is because you're sending the server whatever the client has written in the console, and the server sends it back to all of the clients (including the sender).
So you're writing a message in the console (and you see it) and then you're receiving it back as one of the clients (and you see it again).
A simple fix would be not to send the just received message back to the client (he already sees it in the console). Add this to the Server.AcceptClient#run method:
for (int i = 0; i < ClientSockets.size(); i++) {
Socket pSocket = (Socket) ClientSockets.elementAt(i);
if(ClientSocket.equals(pSocket)){
continue;
}
...

Stratum connection for bitcoin pool mining

I'm programming a Bitcoin miner that mines in a pool using the stratum protocol (see documentation here.
The stratum protocol uses JSON-RPC 2.0 as it's encoding and according to the JSON-RPC 2.0 specification(specification here) I should use sockets to create a connection to the pool.
My problem is that I don't seem to be able to receive a response back from the pool. JSON-RPC 2.0 states that for every Request object that I send, I must receive a response back.
Here is my code:
public static void main(String[] args)
{
connectToPool("stratum.slushpool.com", 3333);
}
static void connectToPool(String host, int port)
{
try
{
InetAddress address = InetAddress.getByName(host);
out.println("Atempting to connect to " + address.toString() + " on port " + port + ".");
socket = new Socket(address, port);
String message1 = "{\"jsonrpc\" : \"2.0\", \"id\": 1, \"method\": \"mining.subscribe\", \"params\": []}";
PrintWriter output = new PrintWriter(socket.getOutputStream(), true);
BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
output.write((message1 + "\\n"));
out.println(input.readLine());//Hangs here.
}
catch (IOException e)
{
out.println(e.getMessage());
out.println("Error. Can't connect to Pool.");
System.exit(-2);
}
}
After hours of tinkering around I have found the solution.
Apparently the JSON string shouldn't have any spaces. So instead of:
String message1 = "{\"jsonrpc\" : \"2.0\", \"id\": 1, \"method\": \"mining.subscribe\", \"params\": []}";
It should be:
String message1 = "{\"id\":1,\"method\":\"mining.subscribe\",\"params\":[]}";
Ok guys .. this is the full running code. Enjoy.
import java.io.PrintWriter;
import java.net.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
public class StratumSubscribe {
public static void main(String[] args)
{
connectToPool("sha256.hk.nicehash.com", 3334);
}
static void connectToPool(String host, int port)
{
try
{
InetAddress address = InetAddress.getByName(host);
System.out.println("Atempting to connect to " + address.toString() + " on port " + port + ".");
Socket socket = new Socket(address, port);
String message1 = "{\"id\":1,\"method\":\"mining.subscribe\",\"params\":[]}";
PrintWriter output = new PrintWriter(socket.getOutputStream(), true);
BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
output.println((message1));
System.out.println(input.readLine());//Hangs here.
}
catch (IOException e)
{
System.out.println(e.getMessage());
System.out.println("Error. Can't connect to Pool.");
System.exit(-2);
}
}
}

Java socket connection receiving and sending String and Object

I've created a client, a server and an object called CcyData. When the client connects to the server I would like the server the send a "Welcome message" like "Hello, you are client# " + clientNumber. as a String and then send an object CcyData. I've managed to get the sending of the CcyData object to work but when I try to read in the "Welcome message" with
input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
System.out.println("Welcome message from server: "+ input.readLine());
the client stops working, nothing happens. No error message. Below is my code. How can I solve this?
Server.
package net.something;
import java.io.IOException;
import java.net.ServerSocket;
public class SocketServer {
private ServerSocket serverSocket = null;
private int clientNumber = 0;
public SocketServer() {
}
public void listenSocket () {
int clientNumber = 0;
try{
serverSocket = new ServerSocket(9090);
System.out.println("Server started on port 9090");
} catch(IOException e) {
e.printStackTrace();
}
while (true) {
ClientSocket clientSocket;
try{
clientSocket = new ClientSocket(serverSocket.accept(), serverSocket, clientNumber++);
Thread thread = new Thread(clientSocket);
thread.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Class ClientSocket
package net.something;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class ClientSocket implements Runnable {
private Socket clientSocket;
private ServerSocket serverSocket;
private int clientNumber;
public ClientSocket(Socket clientSocket, ServerSocket serverSocket, int clientNumber) {
this.clientSocket = clientSocket;
this.serverSocket = serverSocket;
this.clientNumber = clientNumber;
System.out.println("New connection with client# " + clientNumber + " at " + clientSocket);
}
public void run() {
PrintWriter out;
ObjectOutputStream outObjectStream;
try {
out = new PrintWriter(clientSocket.getOutputStream());
out.println("Hello, you are client# " + clientNumber);
outObjectStream = new ObjectOutputStream(clientSocket.getOutputStream());
CcyData ccyData = new CcyData("EUR", 9.56);
System.out.println("CcyData: " + ccyData.getCcy() + " " + ccyData.getFxRate());
outObjectStream.writeObject(ccyData);
} catch (IOException e) {
e.printStackTrace();
}
}
public void finalize() {
try{
serverSocket.close();
System.out.println("Server socket closed");
} catch (IOException e) {
e.printStackTrace();
}
}
}
Client
package net.something;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.net.Socket;
public class SocketClient {
private Socket socket = null;
private BufferedReader input;
private ObjectInputStream inObjectStream = null;
public SocketClient() {
}
public void connectToServer() {
try{
socket = new Socket("127.0.0.1", 9090);
input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
System.out.println("Welcome message from server: "+ input.readLine());
inObjectStream = new ObjectInputStream(socket.getInputStream());
CcyData ccyData = (CcyData) inObjectStream.readObject();
System.out.println(ccyData.getCcy() + " " + ccyData.getFxRate());
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
finalize is only called when the JVM garbage collector decides that there are no more references to your thread and disposes it. Thus, you cannot ensure that finalize will be called when your thread has reached the end of its run() method. Try closing the socket in the run method instead!

Server-Client chat program

I am writing a server-client chat program.
Here is my code
SERVER:
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class HelloServer {
public final static int defaultPort = 2345;
public static void main(String[] args) {
int port = defaultPort;
try {
port = Integer.parseInt(args[0]);
} catch (Exception e) {
}
if (port <= 0 || port >= 65536) {
port = defaultPort;
}
try {
ServerSocket ss = new ServerSocket(port);
while (true) {
try {
Socket s = ss.accept();
String response = "Hello " + s.getInetAddress() + " on port " + s.getPort()
+ "\r\n";
response += "This is " + s.getLocalAddress() + " on port " + s.getLocalPort()
+ "\r\n";
OutputStream out = s.getOutputStream();
out.write(response.getBytes());
System.out.write(response.getBytes());
InputStream in = s.getInputStream();
System.out.println("from client");
int z = 0;
while ((z = in.read()) != -1) {
System.out.write(z);
}
} catch (IOException e) {
}
}
} catch (IOException e) {
System.err.println(e);
}
}
}
CLIENT:
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class SocketGetINetAdd {
public static void main(String[] args) throws UnknownHostException, IOException {
Socket socket = new Socket("192.xxx.x.xxx", 2345);
InetAddress inetAddress = socket.getInetAddress();
System.out.println("Connected to:: " + inetAddress.getHostName() + " Local address:: "
+ socket.getLocalAddress() + " Local Port:: " + socket.getLocalPort());
BufferedInputStream bfINPUT = new BufferedInputStream(socket.getInputStream());
int b = 0;
OutputStream os = System.out;
while ((b = bfINPUT.read()) != -1) {
os.write(b);
}
OutputStream osNew = socket.getOutputStream();
String s = "This Is The Client"; // data to be sent
osNew.write(s.getBytes());
os.write(s.getBytes());
}
I've connected them through my program.
But now I want to know How to send some data back to the server from client?
What would be the code for client(for sending data to server) and also the code for the server for showing the data received from the client on the console(server)?
P.S- I am a novice in network programming. Please do not criticize my coding style :P
Use server stream
OutputStream os = socket.getOutputStream();
instead of client console output stream
OutputStream os = System.out;
at client side to write back to server.
and at server side use client stream to read from client in the same manner.
InputStream in = s.getInputStream();
I have already posted a sample code on server-client communication. Read it for your learning.
You need threads. The client in this examples read the lines from the System.in and sends the line to the server. The server sends an echo.
In your real application you have to take a look of the encoding
Server
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class HelloServer {
public final static int defaultPort = 2345;
public static void main(String[] args) {
int port = defaultPort;
try {
port = Integer.parseInt(args[0]);
} catch (Exception e) {
}
if (port <= 0 || port >= 65536) {
port = defaultPort;
}
try {
ServerSocket ss = new ServerSocket(port);
while (true) {
try {
Socket s = ss.accept();
new SocketThread(s).start();
} catch (IOException e) {
}
}
} catch (IOException e) {
System.err.println(e);
}
}
public static class SocketThread extends Thread {
private Socket s;
public SocketThread(Socket s) {
this.s = s;
}
#Override
public void run() {
try {
String response = "Hello " + s.getInetAddress() + " on port "
+ s.getPort() + "\r\n";
response += "This is " + s.getLocalAddress() + " on port "
+ s.getLocalPort() + "\r\n";
OutputStream out = s.getOutputStream();
out.write(response.getBytes());
BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
while (true) {
String line = input.readLine();
System.out.println("IN: " + line);
s.getOutputStream().write(("ECHO " + line + "\n").getBytes());
s.getOutputStream().flush();
System.out.println(line);
}
} catch (IOException e) {
System.err.println(e);
}
}
}
}
Client
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class SocketGetINetAdd {
public static void main(String[] args) throws UnknownHostException, IOException {
Socket socket = new Socket("localhost", 2345);
InetAddress inetAddress = socket.getInetAddress();
System.out.println("Connected to:: " + inetAddress.getHostName() + " Local address:: " + socket.getLocalAddress() + " Local Port:: " + socket.getLocalPort());
new OutputThread(socket.getInputStream()).start();
InputStreamReader consoleReader = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(consoleReader);
while (true) {
String inline = in.readLine();
if (inline.equals("by")) {
break;
}
inline += "\n";
socket.getOutputStream().write(inline.getBytes());
socket.getOutputStream().flush();
}
}
public static class OutputThread extends Thread {
private InputStream inputstream;
public OutputThread(InputStream inputstream) {
this.inputstream = inputstream;
}
#Override
public void run() {
BufferedReader input = new BufferedReader(new InputStreamReader(inputstream));
while (true) {
try {
String line = input.readLine();
System.out.println(line);
} catch (IOException exception) {
exception.printStackTrace();
break;
}
}
}
}
}

Categories