How to create a simple Server Client Application Using RUDP in Java? - java

I was working on a simple application to transfer files between two machines using UDP, but that turned out to be lossy and unreliable, so while searching the Internet I found this project named Simple Reliable UDP here, but they don't have any documentation or any example code. So if there is any who can help me with this code I will be grateful because I'm newbie in Java. I started with writing simple server client app, but I got address already bind exception. To make clear I want to use UDP connections only that's why I'm trying to implement ReliableServerSocket and ReliableSocket.
package stackoverflow;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.rudp.ReliableServerSocket;
import net.rudp.ReliableSocket;
/**
*
* #author Nika
*/
public class udpServer implements Runnable{
ReliableServerSocket rss;
///ocket rs;
ReliableSocket rs;
public udpServer() throws IOException {
rss= new ReliableServerSocket(9876);
}
public void run(){
while (true){
try {
rs=(ReliableSocket)rss.accept();
System.out.println("Connection Accepted");
System.out.println(""+rs.getInetAddress());
BufferedReader inReader = new BufferedReader (new InputStreamReader (rs.getInputStream()));
//BufferedWriter outReader = new BufferedWriter (new OutputStreamWriter (rs.getOutputStream()));
String str= ""+inReader.readLine();
if(str.contains("UPLOAD")){
System.out.println("Client wants to upload file");
}else if(str.contains("D1")){
System.out.println("Client wants to download file");
}
} catch (IOException ex) {
Logger.getLogger(udpServer.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public static void main(String args[]) throws Exception
{
System.out.println("UDP Server Executed");
Thread t= new Thread( new udpServer());
t.start();
}
}
Client Code here
package stackoverflow;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import net.rudp.ReliableSocket;
/**
*
* #author Nika
*/
public class UdpFileClient {
BufferedWriter outReader;
ReliableSocket server;
public UdpFileClient(boolean b1, boolean b2) throws IOException {
if (b1) {
server = new ReliableSocket("127.0.0.1", 9876);
outReader = new BufferedWriter(new OutputStreamWriter(server.getOutputStream()));
outReader.write("D1");
System.out.println("Download Req Sent From Client");
server.close();
outReader.flush();
outReader.close();
}
if (b2) {
server = new ReliableSocket("127.0.0.1", 9876);
outReader = new BufferedWriter(new OutputStreamWriter(server.getOutputStream()));
outReader.write("UPLOAD");
System.out.println("Upload Req Sent From Client");
server.close();
outReader.flush();
outReader.close();
}
}
public static void main(String args[]) throws Exception {
System.out.println("UDP CLient Executed");
new UdpFileClient(true, true);
}
}
I already know I can use TCP/IP, but it is kind of requirement for the project to use UDP. If any other way to send files in lossless way using UDP with good speed will also be helpful.
Thanks in advance!!

I tried RUDP and found that i was not printing my output, i know this is a silly mistake.
UDP Client
package UDPClient;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import net.rudp.ReliableSocket;
/**
*
* #author Nika
*/
public class UDPtestc {
ReliableSocket server;
public UDPtestc() throws IOException {
server = new ReliableSocket();
server.connect(new InetSocketAddress("127.0.0.1", 9876));
byte[] buffer = new byte[1024];
int count,progress=0;
InputStream in = server.getInputStream();
while((count=in.read(buffer)) >0){
progress+=count;
System.out.println(""+progress);
}
server.close();
}
public static void main(String[] args) throws IOException {
new UDPtestc();
}
}
UDPserver
package UDPServer;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.rudp.ReliableServerSocket;
import net.rudp.ReliableSocket;
/**
*
* #author Nika
*/
public class UDPtests implements Runnable {
ReliableServerSocket rss;
ReliableSocket rs;
String file;
FileInputStream bin;
public UDPtests() throws IOException {
rss = new ReliableServerSocket(9876);
Thread serverthread = new Thread(this);
serverthread.start();
}
public void run() {
while (true) {
try {
rs = (ReliableSocket)rss.accept();
System.out.println("Connection Accepted");
System.out.println("" + rs.getRemoteSocketAddress());
file = "";
Long size=0L;
file += "10MB.txt";
size+=10*1024*1024;
RandomAccessFile r1= new RandomAccessFile(file,"rw");
r1.setLength(size);
byte[] sendData = new byte[1024];
OutputStream os = rs.getOutputStream();
//FileOutputStream wr = new FileOutputStream(new File(file));
bin= new FileInputStream(file);
int bytesReceived = 0;
int progress = 0;
while ((bytesReceived = bin.read(sendData)) > 0) {
/* Write to the file */
os.write(sendData, 0, bytesReceived);
progress += bytesReceived;
System.out.println(""+progress);
}
} catch (IOException ex) {
Logger.getLogger(udpServer.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public static void main(String[] args) throws IOException {
new UDPtests();
}
}
Soon i will post other tuts on RUDP if it will be possible.

Related

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.

Errorwhen WriteObject from Server To Socket

Some one help me this this exception when send object from server to client
it is NotSerializableException <<
and i try to solve the error and implements the interface Serializable and same exception >> >>> >
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package test;
import java.io.FileWriter;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* #author Haz
*/
public class Server {
boolean isRunning = true;
public static final int Port = 500;
public static final String Address = "127.0.0.1";
ObjectOutputStream outToClient;
Socket Client;
ArrayList<ConnectionHandler> Handlers;
HashSet<Socket> Callers;
public Server() throws IOException {
ServerSocket socketSer = new ServerSocket(500);
ExecutorService service = Executors.newFixedThreadPool(50);
Handlers = new ArrayList<>();
Callers = new HashSet<>();
while (isRunning) {
Client = socketSer.accept();
System.out.println("Client Connect on Sever");
ConnectionHandler handler = new ConnectionHandler(Client,socketSer);
Handlers.add(handler);
Callers.add(Client);
SendConnectToAll(Handlers);
}
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException {
// TODO code application logic here
new Server();
}
private void SendConnectToAll(ArrayList<ConnectionHandler> Handlers){
try {
outToClient = new ObjectOutputStream(Client.getOutputStream());
outToClient.writeObject(Handlers);
outToClient.flush();
outToClient.close();
} catch (IOException ex) {
Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package test;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.net.Socket;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* #author Haz
*/
public class SocketClient {
Socket Client;
ObjectInputStream inputFromServer;
public SocketClient(String Address,int Port) {
try {
Client = new Socket(Address,Port);
} catch (IOException ex) {
Logger.getLogger(SocketClient.class.getName()).log(Level.SEVERE, null, ex);
}
new Thread(new Runnable(){
#Override
public void run() {
Object temp =null;
try {
inputFromServer = new ObjectInputStream(Client.getInputStream());
temp =inputFromServer.readObject();
while((temp)!=null){
temp = inputFromServer.readObject();
System.out.println(temp);
}
inputFromServer.close();
} catch (IOException ex) {
Logger.getLogger(SocketClient.class.getName()).log(Level.SEVERE, null, ex);
} catch (ClassNotFoundException ex) {
Logger.getLogger(SocketClient.class.getName()).log(Level.SEVERE, null, ex);
}
}
}).start();
}
}
and class ConnectionHandler it is empty but i implements
public class ConnectionHandler implements Runnable,Serializable {
private Socket Client;
private ServerSocket Server;
public ConnectionHandler(Socket Client, ServerSocket Server) {
this.Client = Client;
this.Server = Server;
}
ConnectionHandler is not serializable because it contains references to Socket and ServerSocket, which are not serializable. You would have to write your own serialization and deserialization methods to make it serializable.
However, it doesn't make sense to make it serializable anyway, since it doesn't have any serializable data in it to transmit over the network.

String data from a Scanner through a PrintWriter

I am trying to pass data from a String into a PrintWriter while simultaneously reading from a BufferedReader between two classes named Server.java and Client.java. My problem is that I am having trouble handling the exceptions that are being thrown from the block of code that reads data from the Scanner object (marked below).
Client.java
package root;
/**
* #author Noah Teshima
*/
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.util.Scanner;
public class Client {
private Socket clientSocket;
private BufferedReader bufferedReader;
private InputStreamReader inputStreamReader;
private PrintWriter printWriter;
private Scanner scanner;
public static void main(String[] args) {
new Client("localhost", 1025);
}
public Client(String hostName, int portNumber) {
try {
this.clientSocket = new Socket(hostName, portNumber);
this.bufferedReader = new BufferedReader(this.inputStreamReader = new InputStreamReader(this.clientSocket.getInputStream()));
this.printWriter = new PrintWriter(clientSocket.getOutputStream());
String msg = "",
msg2 = "";
this.printWriter.println(this.getClass());
this.printWriter.flush();
System.out.println(this.getClass().getName() + " is connected to " + this.bufferedReader.readLine());
while(!(msg = this.scanner.nextLine()).equals("exit")) { //Source of problem
this.printWriter.println(this.getClass().getName() + ": " + msg);
this.printWriter.flush();
while((msg2 = this.bufferedReader.readLine()) != null) {
System.out.println(msg2);
}
}
this.clientSocket.close();
}catch(IOException exception) {
exception.printStackTrace();
}
}
}
Stack trace::
Exception in thread "main" java.lang.NullPointerException
at root.Client.<init>(Client.java:47)
at root.Client.main(Client.java:25)
The code used to read from the BufferedReader and write to a PrintWriter is the same for both classes, so I only posted Client.java. If anyone would like to see the other class file, I would be happy to do so.
Before you use
while(!(msg = this.scanner.nextLine()).equals("exit")) { //Source of problem
You should have initialized the scanner.
The scanner object is null when you used it, and hence the NullPointerException.
I do not see a scanner = new Scanner(...); anywhere within your code,
maybe you have forgetten about it?

Sockets java - Beginner

I'm starting in java and have a problem with sockets, I wanted my server Meet and greet a value and then wanted to turn it into a String, to then include in a conditionif. However, despite the server approved the text without problem, I can not pass the value for a String.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package javasockets;
import java.io.DataInputStream;
import java.io.IOException;
import static java.lang.System.exit;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
/**
*
* #author Nuno
*/
public class JavaSockets {
public static String T = "s";
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException {
// TODO code application logic here
try {
ServerSocket sckServer = new ServerSocket(5000);
System.out.println("Porta 5000 aberta!");
Socket sck;
while (true) {
sck = sckServer.accept();
try (Scanner entrada = new Scanner(sck.getInputStream())) {
while (entrada.hasNextLine()) {
System.out.println(entrada.nextLine());
}
String texto = entrada.nextLine();
System.out.println("ola" + texto);
String fnames = texto;
System.out.println("ola" + fnames);
System.out.println(texto);
if (texto.equals(T)) {
System.out.println("LOOL");
}
}
sckServer.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Cliente code, send messages to the socket 127.0.0.1", 5000
package javasockets;
import java.io.IOException;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* #author Nuno
*/
public class cliente {
public static void main(String[] args) throws IOException {
while (true) {
Socket cliente = new Socket("127.0.0.1", 5000);
System.out.println("O cliente se conectou ao servidor!");
Scanner teclado = new Scanner(System.in);
PrintStream saida = new PrintStream(cliente.getOutputStream());
while (teclado.hasNextLine()) {
saida.println(teclado.nextLine());
}
saida.flush();
saida.close();
teclado.close();
}
}
static Object getInetAddress() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
thanks for the help
Every call to nextLine () method, the server waits to receive a new string, but in the implementation of your client will only send a single string.
So try:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import java.io.DataInputStream;
import java.io.IOException;
import static java.lang.System.exit;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
/**
*
* #author Nuno
*/
public class JavaSockets {
public static String T = "s";
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException {
// TODO code application logic here
try {
ServerSocket sckServer = new ServerSocket(5000);
System.out.println("Porta 5000 aberta!");
Socket sck;
while (true) {
sck = sckServer.accept();
try (Scanner entrada = new Scanner(sck.getInputStream())) {
while (entrada.hasNextLine()) {
String texto = entrada.nextLine();
System.out.println(texto);
System.out.println("ola" + texto);
String fnames = texto;
System.out.println("ola" + fnames);
System.out.println(texto);
if (texto.equals(T)) {
System.out.println("LOOL");
}
}
}
sckServer.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

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