Socket connection succeeds even with wrong/null URL - java

I am running a test using the Java socket class, but somehow my socket.connect ALWAYS connects successfully to something, even if my url variable is null or incorrect. Does anyone know why?
package ping_run_send;
import java.util.*;
import java.lang.*;
import java.net.*;
import java.io.*
import java.security.cert.*;
import javax.net.ssl.*;
public class tcpping {
private String url, status;
private Date timestamp;
private long rtime;
tcpping(String input_url){
this.url = input_url;
}
void ping() {
try{
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("my proxy", 80));
Socket socket = new Socket(proxy);
long tStart = System.currentTimeMillis();
socket.connect(new InetSocketAddress(url, 80),2000);
long tEnd = System.currentTimeMillis();
rtime = tEnd-tStart;
timestamp = new Date(tStart);
InputStream sIn = socket.getInputStream();
if (sIn != null) {
status = "normal";
socket.close();
}else {
status = "error";
}
} catch(final MalformedURLException e){
status = "error";
} catch(IOException e){
status = "error";
}
}
Long get_rtime() {
return rtime;
}
Date get_timestamp() {
return timestamp;
}
String get_status() {
return status;
}
}
I also tried changing the if statement from isConnected() to
InputStream sIn = socket.getInputStream();
if (sIn != null) {
status = "normal";
socket.close();
}else {
status = "error";
}
But nothing seems to be have changed on its ability to detect connection error.
my testing file:
package ping_run_send;
import java.lang.*;
import java.util.*;
import java.io.*;
import ping_run_send.httpping;
public class main {
public static void main(String[] args){
String url = "http://google.com";
//urls like "",http://gowegwgwoJOIJOI03OINEPJPogle.#(*%" all works somehow
tcpping testTcp = new tcpping(url);
testTcp.ping();
System.out.println("tcp ping:");
System.out.println(testTcp.get_rtime());
System.out.println(testTcp.get_timestamp());
System.out.println(testTcp.get_status());
}
}

It is connecting to the Proxy. When you specify a Proxy the connection is made to the Proxy and the Proxy itself handles the connections to the real endpoint.

Related

java.io.EOFException when using sockets with blockchain in java

i have to do a practice in my uni, it must create a blockchain using sockets and serialization in a "simple way". But when exiting the loop (typing "NO") It creates a EOF exception that i cannot solve, while closing the socket(s.close()). i would appreciate some help, i am not vry good at java. here are my classes.
Client
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;
public class Client implements Runnable{
public static void main(String[] args) throws Exception {
(new Thread(new Client())).start();
}
public static MedicalReport createReport(){
return new MedicalReport(10,"pepe","id","record");
}
#Override
public void run() {
// int port = 12345;
// String computer = "localhost";
try{
Socket s = new Socket("localhost", 12348);
ObjectOutputStream p = new ObjectOutputStream(s.getOutputStream());
ObjectInputStream in = new ObjectInputStream(s.getInputStream());
/* PrintWriter print = new PrintWriter(s.getOutputStream());
print.println("ready");
print.flush();*/
//manda informe al servidor serializado y espera respuesta
boolean stop = false;
while(!stop){
try{
MedicalReport report = createReport();
p.writeObject(report);
p.flush();
p.reset();
System.out.println("Do you want to continue? Yes or No");
Scanner in1 = new Scanner (System.in);
String answer="";
if(in1.hasNextLine())
answer = in1.nextLine();
if(!answer.equalsIgnoreCase("yes")){
System.out.println(report);
stop = true;
}
}
catch(Exception e){
System.out.println(e);
}
}
try{
s.close();
}
catch(Exception e){
System.out.println(e);
}
}catch(Exception e){
System.out.println(e);
}
}
}
SERVER
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Scanner;
public class Server {
public static void main(String[] args)
throws Exception
{
ArrayList<Block> blockChain = new ArrayList<>();
try{
ServerSocket ss = new ServerSocket(12348);
Socket s = ss.accept();
ObjectOutputStream out = new ObjectOutputStream(s.getOutputStream());
ObjectInputStream in = new ObjectInputStream(s.getInputStream());
/* Scanner scanner = new Scanner(s.getInputStream());
String text = scanner.nextLine();*/
int i = 0;
int previousHash = 0;
while (i != 20){
MedicalReport rp = (MedicalReport)in.readObject();
Block block = new Block(rp,previousHash);
blockChain.add(block);
System.out.println("Block " + blockChain.size() + " added to blockchain");
System.out.println(blockChain.get(i));
previousHash = block.getBlockHash();
System.out.println(blockChain);
i++;
}
try{
ss.close();
}
catch(Exception e){
System.out.println(e);
}
}catch(Exception e){
System.out.println(e);
}
}
}
It looks like the error is while closing the socket, any idea?
EDIT REST OF THE CODE
MEDICAL REPORT
import java.io.Serializable;
public class MedicalReport implements Serializable {
private int age;
private String name;
private String id;
private String record;
private static final long serialVersionUID = 1L;
public MedicalReport(){super();}
public MedicalReport(int age, String name, String id, String record) {
super();
this.age = age;
this.name = name;
this.id = id;
this.record = record;
}
public String getRecord(){
return this.record;
}
public String toString(){
return this.name + ". \n" + this.age + ". \n" + this.id + ". \n" + this.record;
}
}
BLOCK
public class Block {
private int blockHash;
private int previousHash;
private MedicalReport report;
//Block Constructor.
public Block(MedicalReport report,int previousHash ) {
this.previousHash = previousHash;
this.report = report;
this.blockHash = report.hashCode();
}
public int getPreviousHash() {
return previousHash;
}
public MedicalReport getReport() {
return report;
}
public int getBlockHash() {
return blockHash;
}
}
EDIT 2
FIRST QUESTION SOLVED. Now i get this error when exiting the loop:
java.net.SocketException: Connection reset by peer: socket write error
readObject() throws EOFEzception when the peer has closed the connection. This is normal. Catch it and stop reading. There is no problem here to solve.
IMPORTANT: As EJP said EOFException is normal and you can control the flow of your code with it but if you still want to know how to do in the way you asked here it is. REMEMBER THIS IS JUST FULFILL YOUR QUESTION AND NOT ADVISED TO DO SO.
On Server Class
Replace
MedicalReport rp = (MedicalReport)in.readObject();
With
MedicalReport rp;
if((rp = (MedicalReport)in.readObject())==null) break;
On Client Class
ADD
p.writeObject(null);
Just above the s.close(); statement
You must know that when a peer close the connection normally then
read() returns -1,
readLine() returns null,
readXXX() throws EOFException for any other XXX
And A write will throw an IOException

Cannot reconnect to bluetooth server without restarting bluetooth radio

I have an android client device that will attempt to connect to a bluetooth-enabled server and transmit data to it. So far, it's been working great except for one hitch: whenever I want to reconnect to the server after the connection was terminated, the server does not detect that a request for connection was sent by the client. If I turn off and on the bluetooth radio, and then attempt to reconnect, everything works normally. What am I doing wrong?
Here's the main Class
package org.team2180.scoutingServer;
import java.io.IOException;
import javax.bluetooth.*;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
import javax.microedition.io.StreamConnectionNotifier;
import org.json.JSONObject;
import javax.bluetooth.UUID;
public class Server {
public static final UUID serviceUUID = new UUID("94f39d297d6d437d973bfba39e49d4ee", false);
public static String connectionString = "btspp://localhost:" + serviceUUID.toString() +";name=ProblemServer";
static LocalDevice locDev;
public static final JSONObject DATA = new JSONObject();
public static void main(String[] args) {
try {
locDev = LocalDevice.getLocalDevice();
System.out.println("Local Device: '" + locDev.getFriendlyName()+"' # "+locDev.getBluetoothAddress());
StreamConnectionNotifier streamConnNot = startServer();
startListening(streamConnNot);
} catch (Exception e) {
e.printStackTrace();
}
}
public static StreamConnectionNotifier startServer() throws Exception {
if(serverStarted){return null;}
boolean isNowDiscoverable = locDev.setDiscoverable(DiscoveryAgent.GIAC);
System.out.println("Local Device Discoverable: "+Boolean.toString(isNowDiscoverable));
System.out.println("Local Device URI: "+connectionString);
StreamConnectionNotifier streamConnNot = (StreamConnectionNotifier) Connector.open(connectionString);
System.out.println("Server: Created, waiting for clients . . . ");
return streamConnNot;
}
public static void startListening(StreamConnectionNotifier streamConnNot) throws IOException {
while(true) {
StreamConnection connection = streamConnNot.acceptAndOpen();
Thread connectedThread = new Thread(new ConnectionHandler(connection, TEAM_DATA));
System.out.println("Sever: found a client, placed on thread:" + connectedThread.getId());
connectedThread.start();
}
}
}
I handle each connection with its own thread based on this Class, exchanging an initial byte to determine how to handle the connection (send data to the device's database, get data from the device's database)
package org.team2180.scoutingServer;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Iterator;
import javax.microedition.io.StreamConnection;
import javax.bluetooth.RemoteDevice;
import org.json.*;
public class ConnectionHandler implements Runnable {
final StreamConnection connection;
final JSONObject TEAM_DATA;
RemoteDevice remDev;
String deviceIndex;
public ConnectionHandler(StreamConnection connection,JSONObject TEAM_DATA) {
this.connection = connection;
this.TEAM_DATA = TEAM_DATA;
try {
this.remDev = RemoteDevice.getRemoteDevice(connection);
this.deviceIndex = remDev.getFriendlyName(true)+'#'+remDev.getBluetoothAddress();
} catch (IOException e) {
this.remDev = null;
this.deviceIndex = null;
}
}
#Override
public void run() {
try {
OutputStream out = connection.openOutputStream();
InputStream in = connection.openInputStream();
PrintWriter pWriter = new PrintWriter(new OutputStreamWriter(out));
BufferedReader bReader = new BufferedReader(new InputStreamReader(in));
int handshake = in.read();
if(handshake==1) {
System.out.println(deviceIndex+" will now inform you of TOP SECRET_INFO");
updateDatabase(remDev, pWriter, bReader);
System.out.println(deviceIndex+" >\n"+ TEAM_DATA.getJSONObject(deviceIndex).getInt("entryCount"));
}
} catch (Exception e) {
System.out.println(deviceIndex+"'s thread is terminating BADLY!");
try {connection.close();} catch (IOException e1) {e1.printStackTrace();}
return;
}
System.out.println(deviceIndex+"'s thread is terminating!");
return;
}
public void updateDatabase(RemoteDevice remDev, PrintWriter ex, BufferedReader in) throws IOException, JSONException {
//OK!
ex.write(1);
ex.flush();
char[] charData = new char[8192];
in.read(charData);
String data = new String(charData);
connection.close();
//Continue doing other things with data
.
.
.
Here is the Android client code to connect to the server.It is not a thread, and does block, however, this is intentional so that the user waits before leaving the connection radius
sendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String text = gatherData();
try{
bS = getSockToServer();
bS.connect();
OutputStream bsO = bS.getOutputStream();
InputStream bsI = bS.getInputStream();
bsO.write(1);//Code upload
bsO.flush();
Log.d("sendButton.onClick","sent condition code 1");
int handRespond = (int)bsI.read();
Log.d("recieved",handRespond+"");
if(handRespond == 1){
bsO.write(text.getBytes("UTF-8"));
bsO.flush();
}
}catch(Exception e){
Log.e("sendButton.onClick",e.toString());
try{
bS.close();
}catch(IOException ioE){
Log.e("sendButton.onClick{SNC}",e.toString());
}
}
}
});
My final goal would be to handle multiple devices at once (hence the usage of threads) and not have to reset the radio every time a device needs to reconnect.
My code extremely crude; I have only been working with bluecove (and bluetooth in general) for two weeks. Any advice/tricks are appreciated!
I can't relive i didn't see this before.
I need to close the socket clientside.
Whoops.

How are images written to a web server (developing a custom web server in java)

I am developing a web server(experimenting with network programming in java) using Java SE only, everything seems to be working well (i.e HTML and CSS files) but the problem is with images, they are written to browser as bytes with the correct mime type and the correct size but the problem is that they wont display on the web browser, its showing a black Screen, developers tool on Google Chrome shows the image has been properly downloaded with a status code of 200 OK and the correct file size . Below is my code.
package miniserver;
import java.io.*;
import java.io.FileInputStream;
import java.util.Scanner;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.NoSuchElementException;
import java.util.logging.Level;
import java.util.logging.Logger;
enum status_code{
OK(200),NOT_FOUND(404),FORBIDDEN(403);
private int code;
status_code(int code){
this.code=code;
}
public int getCode(){
return this.code;
}
}
public class MiniServer {
public static void main(String[] args) {
try{
InetAddress address = InetAddress.getLocalHost();
try{
ServerSocket webserver = new ServerSocket(1521);
System.out.println("Web Sever Started");
System.out.println("Running On " + address.getHostAddress());
Date k= new Date();
System.out.println(k.toString());
Socket browser ;
while(true){
browser=webserver.accept();
requestHandler handle = new requestHandler(browser);
}
}catch(IOException err){
System.out.println("Server Already Running"+err.getMessage());
}
}catch(UnknownHostException ex){
Logger.getLogger(MiniServer.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
class requestHandler implements Runnable{
static int nRequest=0;
private Socket client;
private BufferedOutputStream stream;
FileOutputStream out;
BufferedOutputStream response;
BufferedReader request;
requestHandler(Socket client){
try{
this.client=client;
this.response=new BufferedOutputStream (client.getOutputStream());
this.request=new BufferedReader( new InputStreamReader(client.getInputStream()));
new Thread(this).start();
}catch(IOException e){
}
}
#Override
public void run(){
try{
Scanner header = new Scanner(this.request);
String rf="";
String firstline=null;
try{
firstline=header.nextLine();
rf =firstline.split("\\s")[1].split("\\?")[0];
System.out.println(rf);
}catch(NoSuchElementException err){
System.out.println("NO HEADERS FOUND"+err.getMessage());
}
fileInputStream page;
fileInputStream errorpage=new fileInputStream("web/index.html");
status_code code=null;
String type="";
if(firstline.startsWith(".5.")){
page=errorpage;
code=status_code.FORBIDDEN;
}else if(rf.equals("/")){
this.out = new FileOutputStream("test/index.html");
type="text/html";
page = new fileInputStream("web/index.html");
code=status_code.OK;
}else{
this.out = new FileOutputStream("test"+rf);
type = mime("web"+rf);
File local = new File("web"+rf);
if(local.exists()){
page=new fileInputStream(local);
code=status_code.OK;
}
else{
page=errorpage;
code=status_code.NOT_FOUND;
}
}
reply(code,page,type);
}catch(IOException e){
System.out.println(e.getMessage());
}
}
void reply(status_code c,fileInputStream file,String type) throws IOException{
StringBuilder head = new StringBuilder();
head.append("HTTP/1.1 "+c.getCode()+" "+c+"\r\n");
head.append("Date: "+ new Date().toString()+"\r\n");
head.append("Server: Kilobyte MiniServer\r\n");
head.append("Connection: close\r\n");
head.append("Content-Type: "+type+" \r\n");
head.append("Content-length: "+file.available()+"\n\r");
head.append("\n\r");
int length=head.length();
for(byte b: head.toString().getBytes()){
this.response.write(b);
}
int pageBytes;
try{
while((pageBytes=file.read()) != -1){
this.response.write(pageBytes);
this.out.write(pageBytes);
}
file.close();
this.response.close();
this.request.close();
}catch(IOException e){
}
}
synchronized int incr(){
this.notifyAll();
return ++nRequest;
}
String mime(String file){
if(file.endsWith("css"))
return "text/css";
else if(file.endsWith("html"))
return "text/html";
else if(file.endsWith("js"))
return "text/javascript";
else if(file.endsWith("JPG"))
return "image/jpg";
else if(file.endsWith("jpg"))
return "image/jpg";
else if(file.endsWith("jpg"))
return "image/jpg";
else if(file.endsWith("png"))
return "image/png";
return "text";
}
}
class fileInputStream extends FileInputStream{
String f;
fileInputStream(String f) throws FileNotFoundException{
super(f) ;
this.f=f;
}
fileInputStream(File f) throws FileNotFoundException{
super(f);
this.f=f.toString();
}
#Override
public String toString(){
return f;
}
}

Java code does not get udp packet in a specific port

I am trying to read some packets from a port 2020 in my server. I have run tcpdump -r eth1 port 2020 and can find that udp packets are coming into the port. Following is the screenshot :
But when i try to read those packets from the java code, i do not get any data. Following is my java code :
package packetreceiver;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import main.Main;
import propertyfilereader.PropertyFileReader;
import org.apache.log4j.Logger;
import com.sun.jmx.snmp.SnmpMessage;
import alarmprocessor.AlarmProcessor;
public class UDPPacketReceiver extends Thread {
private DatagramSocket socket = null;
private Logger logger = Logger.getLogger(UDPPacketReceiver.class);
public boolean dynamicKey = false;
private UDPPacketReceiver() {
try {
logger.debug(" port : " + Main.orgPort);
logger.debug(" ip : " + Main.orgBindIPStr);
logger.debug("creating socket");
socket = new DatagramSocket(null);
//socket = new DatagramSocket(38567);
InetSocketAddress address = new InetSocketAddress(2020);
socket.bind(address);
logger.debug("Receiver Socket created successfully");
} catch (Exception e) {
logger.fatal("Exception at creating socket ", e);
logger.fatal("Exiting successfully ");
System.exit(0);
}
this.running = true;
}
static UDPPacketReceiver instance = null;
public static UDPPacketReceiver getInstance() {
if (instance == null) {
createInstance();
}
return instance;
}
boolean running = false;
private static synchronized UDPPacketReceiver createInstance() {
if (instance == null) {
instance = new UDPPacketReceiver();
}
return instance;
}
public void run() {
byte[] data = new byte[2048];
DatagramPacket packet = new DatagramPacket(data, data.length);
while (this.running) {
try {
logger.debug("waiting for received data");
this.socket.receive(packet);
int length = packet.getLength();
logger.debug("length:"+length);
logger.debug("data:"+new String(packet.getData()));
} catch (Exception e) {
if ((this.socket == null) || (this.socket.isClosed())) {
this.running = false;
} else {
this.logger.fatal("Error in receiving UDP packet:", e);
}
}
}
}
public void shutdown() {
this.running = false;
try {
if ((this.socket != null) && (!this.socket.isClosed())) {
this.socket.close();
}
} catch (Exception localException) {
}
this.socket = null;
}
}
I have searched in stackeoverflow and other posts but could not find any solution. Can you please help me.
Regards,
Tanvir
Check with the netstat command to see whether your application is actually bound to the correct IP/interface:
> sudo netstat -tunlp | grep 2020
works in linux.
You can also change this line:
InetSocketAddress address = new InetSocketAddress(172.22.49.116, 2020);

How to create a java Server that accepts client connections and then build a relay connection for a client pair

I want to create a server that can accept multiple connections and then bind 2 clients as a pair and forward the data between these 2 clients. But it is about multiple pairs of clients. I already have multithread server that can create a new thread for each new connected client. The problem for me is that these threads dont know of each other and somehow I have to connect 2 clients to a connection pair.
For now I just create these pair connection as this: I wait for the first client, then I wait for the second client and then open a thread for the input of client 1 that gets forwarded to client 2 and the other way around. This is not usable for multiple clients.
How can I do this decent?
The way I see it, a client would need to
establish a TCP(?) connection with your server,
identify itself
give the ID of the other client it wishes to talk to
The first that connects would have to be kept on hold (in some global table in your server) until the second client connects.
Once a pair of clients would have been recognized as interlocutors, you would create a pair of threads to forward the data sent by each client to the other one.
UPDATE: Example
ClientSocket.java
package matchmaker;
import java.io.Closeable;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
public class ClientSocket implements Closeable {
private final Socket socket;
private final InputStream in;
private final OutputStream out;
private final String ownId;
private final String peerId;
public ClientSocket(Socket socket) throws IOException {
this.socket = socket;
this.in = socket.getInputStream();
this.out = socket.getOutputStream();
DataInputStream din = new DataInputStream(in);
this.ownId = din.readUTF();
this.peerId = din.readUTF();
}
public ClientSocket(String server, int port, String ownId, String peerId)
throws IOException {
this.socket = new Socket(server, port);
this.socket.setTcpNoDelay(true);
this.in = socket.getInputStream();
this.out = socket.getOutputStream();
this.ownId = ownId;
this.peerId = peerId;
DataOutputStream dout = new DataOutputStream(out);
dout.writeUTF(ownId);
dout.writeUTF(peerId);
}
public String getOwnId() {
return ownId;
}
public String getPeerId() {
return peerId;
}
public InputStream getInputStream() {
return in;
}
public OutputStream getOutputStream() {
return out;
}
#Override
public void close() throws IOException {
socket.close();
}
}
Matchmaker.java: the server
package matchmaker;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Matchmaker extends Thread {
private static final Logger LOG
= Logger.getLogger(Matchmaker.class.getName());
private final int port;
private final Map<ClientPair,ClientSocket> waiting = new HashMap<>();
public static void main(String[] args) {
try {
int port = 1234;
int st = 0;
for (String arg: args) {
switch (st) {
case 0:
switch (arg) {
case "-p":
st = 1;
break;
default:
System.out.println("Unknown option: " + arg);
return;
}
break;
case 1:
port = Integer.parseInt(arg);
st = 0;
break;
}
}
Matchmaker server = new Matchmaker(port);
server.start();
server.join();
} catch (InterruptedException ex) {
LOG.log(Level.SEVERE, null, ex);
}
}
private Matchmaker(int port) {
this.port = port;
setDaemon(true);
}
#Override
public void run() {
try {
ServerSocket server = new ServerSocket(port);
while (true) {
ClientSocket socket = new ClientSocket(server.accept());
ClientPair pair = new ClientPair(
socket.getOwnId(), socket.getPeerId());
ClientSocket other;
synchronized(this) {
other = waiting.remove(pair.opposite());
if (other == null) {
waiting.put(pair, socket);
}
}
if (other != null) {
LOG.log(Level.INFO, "Establishing connection for {0}",
pair);
establishConnection(socket, other);
} else {
LOG.log(Level.INFO, "Waiting for counterpart {0}", pair);
}
}
} catch (IOException ex) {
LOG.log(Level.SEVERE, null, ex);
}
}
private void establishConnection(ClientSocket socket, ClientSocket other)
throws IOException {
Thread thread = new StreamCopier(
socket.getInputStream(), other.getOutputStream());
thread.start();
thread = new StreamCopier(
other.getInputStream(), socket.getOutputStream());
thread.start();
}
}
StreamCopier.java: a thread that reads from an InputStream and writes to an OutputStream
package matchmaker;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
public class StreamCopier extends Thread {
private static final Logger LOG
= Logger.getLogger(StreamCopier.class.getName());
private final InputStream in;
private final OutputStream out;
public StreamCopier(InputStream in, OutputStream out) {
this.in = in;
this.out = out;
setDaemon(true);
}
#Override
public void run() {
LOG.info("Start stream copier");
try {
for (int b = in.read(); b != -1; b = in.read()) {
out.write(b);
}
} catch (IOException ex) {
LOG.log(Level.SEVERE, null, ex);
} finally {
LOG.info("End stream copier");
try {
out.close();
} catch (IOException ex) {
LOG.log(Level.SEVERE, null, ex);
}
}
}
}
ClientPair.java: a pair of client IDs
package matchmaker;
public class ClientPair {
private final String client1;
private final String client2;
public ClientPair(String client1, String client2) {
this.client1 = client1;
this.client2 = client2;
}
public String getClient1() {
return client1;
}
public String getClient2() {
return client2;
}
public ClientPair opposite() {
return new ClientPair(client2, client1);
}
#Override
public int hashCode() {
int hash = 5;
hash = 73 * hash + client1.hashCode();
hash = 73 * hash + client2.hashCode();
return hash;
}
#Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final ClientPair other = (ClientPair) obj;
return client1.equals(other.client1) && client2.equals(other.client2);
}
#Override
public String toString() {
return "[" + client1 + "," + client2 + "]";
}
}
ReaderClient.java: a sample client that reads from the socket and writes to standard output
package matchmaker;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.logging.Level;
import java.util.logging.Logger;
public class ReaderClient {
private static final Logger LOG = Logger.getLogger(ReaderClient.class.getName());
public static void main(String[] args) {
try (ClientSocket client
= new ClientSocket("localhost", 1234, "reader", "writer")) {
Reader reader
= new InputStreamReader(client.getInputStream(), "UTF-8");
BufferedReader in = new BufferedReader(reader);
for (String s = in.readLine(); s != null; s = in.readLine()) {
System.out.println(s);
}
} catch (IOException ex) {
LOG.log(Level.SEVERE, null, ex);
}
}
}
WriterClient.java: a sample client that writes to the socket
package matchmaker;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.logging.Level;
import java.util.logging.Logger;
public class WriterClient {
private static final Logger LOG = Logger.getLogger(ReaderClient.class.getName());
public static void main(String[] args) {
try (ClientSocket client
= new ClientSocket("localhost", 1234, "writer", "reader")) {
Writer writer
= new OutputStreamWriter(client.getOutputStream(), "UTF-8");
PrintWriter out = new PrintWriter(writer);
for (int i = 0; i < 30; ++i) {
out.println("Message line " + i);
}
out.flush();
} catch (IOException ex) {
LOG.log(Level.SEVERE, null, ex);
}
}
}

Categories

Resources