Java (Raspberry pi) Thread - java

I am a student who is studying java.(Especially Raspberry pi) I have a question this multuthread. It can be compiled. But it doesn't work in my kit. If you don't mind guys, could you check my code and help me?
Thanks...
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.SocketAddress;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.io.File;
import java.io.FileWriter;
public class RcvThread2 implements Runnable{
private static final int sizeBuf = 50;
private Socket clientSocket;
private Logger logger;
private SocketAddress clientAddress;
public RcvThread2(Socket clntSock, SocketAddress clientAddress, Logger logger) {
this.clientSocket = clntSock;
this.logger = logger;
this.clientAddress = clientAddress;
}
static class CloseExtends extends Thread {
static final String GPIO_OUT = "out";
static final String GPIO_ON = "1";
static final String GPIO_OFF = "0";
static final String[] GpioChannels = {"18"};
public static void main(String[] args) {
FileWriter[] commandChannels;
try {
FileWriter unexportFile = new FileWriter("sys/class/gpio/unexport");
FileWriter exportFile = new FileWriter("sys/class/gpio/gpio/export");
for(String gpioChannel : GpioChannels) {
System.out.println(gpioChannel);
File exportFileCheck =
new File("sys/class/gpio/gpio" +gpioChannel);
if(exportFileCheck.exists()) {
unexportFile.write(gpioChannel);
exportFile.flush();
}
exportFile.write(gpioChannel);
exportFile.flush();
FileWriter directionFile = new FileWriter("/sys/class/gpio/gpio" + gpioChannel + "/direction");
directionFile.write(GPIO_OUT);
directionFile.flush();
}
FileWriter commandChannel = new FileWriter("sys/class/gpio/gpio" + GpioChannels[0] + "/value");
int period = 20;
int repeatLoop = 25;
int counter;
while(true) {
for(counter = 0; counter < repeatLoop; counter++) {
commandChannel.write(GPIO_ON);
commandChannel.flush();
java.lang.Thread.sleep(2, 20000);
commandChannel.write(GPIO_OFF);
commandChannel.flush();
java.lang.Thread.sleep(period);
}
break;
}
} catch(Exception exception) {
exception.printStackTrace();
}
}
}
public void main(){
try {
InputStream ins = clientSocket.getInputStream();
OutputStream outs = clientSocket.getOutputStream();
int rcvBufSize;
byte[] rcvBuf = new byte[sizeBuf];
while ((rcvBufSize = ins.read(rcvBuf)) != -1) {
String rcvData = new String(rcvBuf, 0, rcvBufSize, "UTF-8");
if(rcvData.compareTo("MotorLock") == 0) {
CloseExtends te = new CloseExtends();
te.start();
}
if(rcvData.compareTo("MotorOpen") == 0) {
}
logger.info("Received data :" + rcvData + " (" + clientAddress + ")");
outs.write(rcvBuf, 0, rcvBufSize);
}
logger.info(clientSocket.getRemoteSocketAddress() + "Closed");
} catch (IOException ex) {
logger.log(Level.WARNING, "Exception in RcvThread", ex);
}finally {
try{
clientSocket.close();
System.out.println("Disconnected! Client IP :" + clientAddress);
} catch (IOException e) {}
}
}
}

The lower main method never gets called.
If you run your program it will execute the public static void main(String[] args) { method.
I think this is the method you want to run in the second thread?!
If you declare and run your new thread using
CloseExtends te = new CloseExtends();
te.start();
it will run the threads public void run() { method.
So if I understand your intention correctly you should change the name of the main method in the CloseExtends class to the threads run method and change the signature of the lower main method to the java programs main method public static void main(String[] args) {.
I would not name any other method "main" if it is not really a main method.
You can see an example of creating a new thread with the Runnable interface here: https://docs.oracle.com/javase/tutorial/essential/concurrency/runthread.html

Related

Using ObjectStreams to send Lists over sockets

I need to transfer a List between nodes and replace the existing one with the new one in the new node to achieve this, I'm using Sockets from Java.
I somehow have managed to transfer the data but only when I terminate the process. I need it to continue running, the process but at the same time transfer, the data in case any other new node joins the List.
How can I achieve this? I will have to introduce Threads in the Download along the road.
I got it working with files but now I need to change it to Sync lists, just having this is enough?
private static List<CloudByte> cloudByteList = Collections.synchronizedList(new ArrayList<>());
This is my current code:
import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import static FileData.getCloudByteList;
import static FileData.getFile;
public class FileData {
private static File file;
private static String fileName;
private static List<CloudByte> cloudByteList = Collections.synchronizedList(new ArrayList<>());
public FileData(String fileName) throws IOException {
if (fileName == null) {
this.fileName = "data2.bin";
this.file = new File(this.fileName);
Download.downloadFile();
} else {
this.file = new File(fileName);
this.fileName = fileName;
fillingList();
}
}
public void fillingList() throws IOException {
byte[] fileContents = Files.readAllBytes(file.toPath());
for (int i = 0; i < fileContents.length - 1; i++) {
cloudByteList.add(new CloudByte(fileContents[i]));
}
}
public static List<CloudByte> getCloudByteList() {
return cloudByteList;
}
public static File getFile() {
return file;
}
public String getFileName() {
return fileName;
}
public static void setFile(File file) {
FileData.file = file;
}
/*--------------------------Download--------------------------*/
}
class Download extends Thread {
static ConnectingDirectory connectingDirectory;
#Override
public void run() {
try {
downloadFile();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void downloadFile() throws IOException {
var nodes = ConnectingDirectory.getNodes();
Socket socket = null;
if (getFile().exists()) {
System.out.println("File: " + getFile() + " exists.");
new Upload().uploadFile();
}
FileOutputStream fos = new FileOutputStream(FileData.getFile());
//ObjectOutputStream oos = new ObjectOutputStream(fos);
for (int i = 0; i < nodes.size() - 1; i++) {
if (!(nodes.get(i).getHostPort() == ConnectingDirectory.getHostIP())) {
System.out.println("test33123");
ServerSocket serverSocket = new ServerSocket(nodes.get(i).getHostPort());
System.out.println(serverSocket);
socket = serverSocket.accept();
System.out.println("now socket");
System.out.println(socket);
//socket = new Socket(nodes.get(i).getName(), nodes.get(i).getHostPort());
//System.out.println(socket);
int bytes = 0;
DataInputStream ois = new DataInputStream(socket.getInputStream());
long size = ois.readLong();
System.out.println(size);
byte[] buffer = new byte[100 * 10000];
while (size > 0 && (bytes = ois.read(buffer, 0, (int) Math.min(buffer.length, size))) != -1) {
System.out.println("test3333");
fos.write(buffer, 0, bytes);
size -= bytes;
}
}
}
}
}
/*--------------------------Upload--------------------------*/
class Upload {
public void uploadFile() throws IOException {
int bytes = 0;
var nodes = ConnectingDirectory.getNodes();
FileInputStream fileInputStream = new FileInputStream("data.bin");
DataInputStream ois = new DataInputStream(fileInputStream);
if (!getFile().exists()) {
System.out.println("File doesn't exist." + "\nDownloading the file!");
new Download().downloadFile();
}
System.out.println("hello");
for (int i = 0; i < nodes.size() - 1; i++) {
System.out.println("hello2");
Socket socket = new Socket(nodes.get(i).getName(), nodes.get(i).getHostPort());
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
dos.writeLong(new File("data.bin").length());
byte[] buffer = new byte[100 * 10000];
while ((bytes = ois.read(buffer)) != -1) {
dos.write(buffer, 0, bytes);
dos.flush();
}
}
}
}
As you can see, I'm using DataInput because if I try to use the ObjectInputStream, I get a Corrupted Header Exception. I have more classes to add to this. My goal is as I said, to transfer the data inside the "data.bin" to a "data2.bin" file. I'm able to create it and delete it but at the same time, no Data is being written/sent to it.
How can I fix the CorruptedHeaderException and get it to send the content?
All help is appreciated.
StorageNode Class:
import java.io.IOException;
import java.util.Scanner;
import java.util.regex.Pattern;
import static FileData.*;
public class StorageNode extends Thread {
private static int serverPort = 8080;
private static int clientPort = 8082;
private static String fileName = null;
private static String addressName = "localhost";
private static ConnectingDirectory connectingDirectory;
private static FileData fileData;
static ErrorInjection errorInjection;
public static void main(String[] args) throws IOException, InterruptedException {
/* if (args.length > 3) {
addressName = args[0];
serverPort = Integer.parseInt(args[1]);
clientPort = Integer.parseInt(args[2]);
fileData = new FileData(args[3]);
} else {
fileName = null;
fileData = new FileData(fileName);
}*/
connectingDirectory = new ConnectingDirectory(addressName, clientPort, serverPort);
fileData = new FileData(fileName);
errorInjection = new ErrorInjection();
errorInjection.start();
if(fileData.getFile().exists()){
new Upload().uploadFile();
}else {
new Download().downloadFile();
}
}
ConnectingDirectory Class
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class ConnectingDirectory {
private String hostName;
private static int hostIP;
private int directoryIP;
private InetAddress address;
private InputStream in;
private OutputStream out;
private static List<Nodes> nodes = new ArrayList<>();
List<String> nodess = new ArrayList<>();
private Socket socket;
private String sign = "INSC ";
public ConnectingDirectory(String hostName, int hostIP, int directoryIP) throws IOException {
this.hostName = hostName;
this.hostIP = hostIP;
this.directoryIP = directoryIP;
this.address = InetAddress.getByName(hostName);
this.socket = new Socket(address, directoryIP);
signUp();
askConnectedNodes();
}
public void signUp() throws IOException {
System.out.println("You are connecting to the following address: " + hostIP + "\n");
System.out.println("The port you are connected to: " + socket.getPort() + "\n");
in = socket.getInputStream();
out = socket.getOutputStream();
out.write(generateSignUp(address, hostIP).getBytes());
out.flush();
}
public String generateSignUp(InetAddress address, int hostIP) {
String signUpString = sign + address + " " + hostIP + "\n";
return signUpString;
}
public void askConnectedNodes() throws IOException {
String directoryNodesAvailable;
String a = "nodes\n";
out.write(a.getBytes());
out.flush();
Scanner scan = new Scanner(in);
while (true) {
directoryNodesAvailable = scan.nextLine();
addExistingNodes(directoryNodesAvailable);
//System.out.println("Eco: " + directoryNodesAvailable);
if (directoryNodesAvailable.equals("end")) {
out.flush();
printNodes();
break;
}
}
}
public void addExistingNodes(String sta) throws IOException {
if (sta.equals("end")) return;
if (!(nodess.contains(sta))) {
nodess.add(sta);
nodes.add(new Nodes(nodess.get(nodess.size() - 1)));
}
return;
}
public static List<Nodes> getNodes() {
return nodes;
}
public void printNodes() {
System.out.println("Checking for available nodes: \n");
nodes.forEach((z) -> System.out.println(z.getNode()));
}
public Socket getSocket() {
return socket;
}
public static int getHostIP() {
return hostIP;
}
public InetAddress getAddress() {
return address;
}
}
For all of those that need help in the future:
Sender side:
Socket socket = new Socket("localhost", hostPort);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
ByteBlockRequest bbr = new ByteBlockRequest(getStoredData());
objectOutputStream.writeObject(bbr.blocksToSend(j));
Receiver side:
Socket = StorageNode.getServerSocket().accept();
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
byte[] bit = (byte[]) ois.readObject();
In my case, I needed to use byte[], so I had to do a few additional functions in the back, to change Cloudbyte[] into byte[]. Once I did that, I was able to send the data using, ObjectInput/ObjectOutput.

How do I fix Illegal Start of Expressions with all of my methods?

I have my code. I think it's all right, but it is not. It keeps telling me at the beginning of each method that there is a ';' expected and it's also an 'illegal start of expression' with the void. I do not know how to fix it. Can someone please help me fix these errors?
Here's an example of the Errors:
F:\COMP SCI\Topic 29 - Data Structures -- Robin Hood\Problem Set\RobinHoodApp.java:203: error: ';' expected
void arrayList **()** throws FileNotFoundException();
F:\COMP SCI\Topic 29 - Data Structures -- Robin Hood\Problem Set\RobinHoodApp.java:212: error: illegal start of expression
**void** output()
F:\COMP SCI\Topic 29 - Data Structures -- Robin Hood\Problem Set\RobinHoodApp.java:212: error: ';' expected
void output **()**
My code:
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import static java.lang.System.out;
import java.util.ArrayList;
import javax.swing.JFrame;
public class RobinHoodApp{
public static void main(String[] args) throws FileNotFoundException, IOException {
RobinHood app = new RobinHood();
app.readFile();
app.arrayList();
app.wordCount();
app.countMenAtArms();
app.writeToFile();
}
}
class RobinHood extends JFrame
{
private static final ArrayList<String>words = new ArrayList<>();
private static Scanner book;
private static int count;
private static int wordCount;
public RobinHood()
{
try {
// scrubber();
//Prints All Words 1 by 1: Works!
book = new Scanner(new File("RobinHood.txt") );
book.useDelimiter("\r\n");
} catch (FileNotFoundException ex)
{
out.println("Where's your text fam?");
}
}
void readFile()
{
while(book.hasNext())
{
String text = book.next();
out.println(text);
}
void arrayList() throws FileNotFoundException();
{
Scanner add = new Scanner(new File("RobinHood.txt"));
while(add.hasNext())
{
words.add(add.next());
}
}
void output()
{
out.println(words);
}
void countMenAtArms()
{
//Shows 23 times
String find = "men-at-arms";
count = 0;
int x;
String text;
for(x=0; x< wordCount; x++ )
{
text = words.get(x);
text = text.replaceAll("\n", "");
text = text.replaceAll("\n", "");
if (text.equals(find))
{
count++;
}
}
out.println("The amount of time 'men-at-arms' appears in the book is: " + count);
}
// void scrubber()
// {
//
// }
//
//
void wordCount()
{
{
wordCount=words.size();
out.println("There are "+wordCount+" words in Robin Hood.");
}
}
public void writeToFile()
{
File file;
file = new File("Dominique.dat");
try (FileOutputStream data = new FileOutputStream(file)) {
if ( !file.exists() )
{
file.createNewFile();
}
String wordCountSentence = "There are "+ wordCount +" words in Robin Hood. \n";
String countTheMen = "The amount of time 'men-at-arms' appears in the book is: " + count;
byte[] strToBytes = wordCountSentence.getBytes();
byte[] menToBytes = countTheMen.getBytes();
data.write(strToBytes);
data.write(menToBytes);
data.flush();
data.close();
}
catch (IOException ioe)
{
System.out.println("Error");
}
}
}
}
You should use a Java IDE like Eclipse when programming Java, it would point out to you the most obvious mistakes in your code.
You missed a } after the while loop for your readFile() method (thanks to Sweeper for this one).
The syntax in your arrayList() method is wrong.
void arrayList() throws FileNotFoundException(); {
No semicolon at the end of this defintion, no parenthesis at the end too, you are describing the class, not a method. Here is the correct way:
void arrayList() throws FileNotFoundException {
1 useless } at the end of your class file.
Find below your code, with a proper layout and without syntax errors. Please use an IDE next time, that would avoid you an awful lot of trouble.
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import static java.lang.System.out;
import java.util.ArrayList;
import javax.swing.JFrame;
public class RobinHoodApp {
public static void main(String[] args) throws FileNotFoundException, IOException {
RobinHood app = new RobinHood();
app.readFile();
app.arrayList();
app.wordCount();
app.countMenAtArms();
app.writeToFile();
}
}
class RobinHood extends JFrame
{
private static final ArrayList<String>words = new ArrayList<>();
private static Scanner book;
private static int count;
private static int wordCount;
public RobinHood()
{
try {
// Prints All Words 1 by 1: Works!
book = new Scanner(new File("RobinHood.txt") );
book.useDelimiter("\r\n");
} catch (FileNotFoundException ex)
{
out.println("Where's your text fam ?");
}
}
void readFile()
{
while(book.hasNext())
{
String text = book.next();
out.println(text);
}
}
void arrayList() throws FileNotFoundException
{
Scanner add = new Scanner(new File("RobinHood.txt"));
while(add.hasNext())
{
words.add(add.next());
}
}
void output()
{
out.println(words);
}
void countMenAtArms()
{
// Shows 23 times
String find = "men-at-arms";
count = 0;
int x;
String text;
for(x=0; x< wordCount; x++ )
{
text = words.get(x);
text = text.replaceAll("\n", "");
text = text.replaceAll("\n", "");
if (text.equals(find))
{
count++;
}
}
out.println("The amount of time 'men-at-arms' appears in the book is: " + count);
}
void wordCount()
{
{
wordCount=words.size();
out.println("There are "+wordCount+" words in Robin Hood.");
}
}
public void writeToFile()
{
File file;
file = new File("Dominique.dat");
try (FileOutputStream data = new FileOutputStream(file)) {
if ( !file.exists() )
{
file.createNewFile();
}
String wordCountSentence = "There are "+ wordCount +" words in Robin Hood. \n";
String countTheMen = "The amount of time 'men-at-arms' appears in the book is: " + count;
byte[] strToBytes = wordCountSentence.getBytes();
byte[] menToBytes = countTheMen.getBytes();
data.write(strToBytes);
data.write(menToBytes);
data.flush();
data.close();
}
catch (IOException ioe)
{
System.out.println("Error");
}
}
}
throws FileNotFoundException();
This should be
throws FileNotFoundException
and similarly in all cases.
Rather trivial. Don't just make up the syntax. Look it up.

Sending a file line by line, in 2 seconds intervals, using ticker behaviours

My question is: How to send a line of a file to another agent every 2 seconds using ticker behaviours?
More specifically, in the first iteration, the agent sends the first line. In the second, the agent sends the second line etc.
My code below:
package pack1;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import jade.core.AID;
import jade.core.Agent;
import jade.core.behaviours.TickerBehaviour;
import jade.lang.acl.ACLMessage;
import jade.wrapper.ControllerException;
public class Agent2 extends Agent {
private static final long serialVersionUID = 1L;
int nombre_ligne = 0;
BufferedReader lecteurAvecBuffer = null;
#Override
protected void setup() {
FileInputStream fis;
try {
fis = new FileInputStream("/home/hduser/Bureau/word.txt");
#SuppressWarnings("resource")
LineNumberReader l = new LineNumberReader(new BufferedReader(
new InputStreamReader(fis)));
while ((l.readLine()) != null) {
nombre_ligne = l.getLineNumber();
}
lecteurAvecBuffer = new BufferedReader(new FileReader(
"/home/hduser/Bureau/esclave1/abc.txt"));
int a = 1;
while (a <= ((int) nombre_ligne) / 3) {
a++;
String word = lecteurAvecBuffer.readLine();
addBehaviour(new TickerBehaviour(this, 2000) {
private static final long serialVersionUID = 1L;
#Override
protected void onTick() {
ACLMessage message = new ACLMessage(ACLMessage.INFORM);
message.addReceiver(new AID("agent1", AID.ISLOCALNAME));
message.setContent(word);
send(message);
}
});
a++;
}
lecteurAvecBuffer.close();
} catch (FileNotFoundException exc) {
System.out.println("Erreur d'ouverture");
} catch (IOException e) {
e.printStackTrace();
}
}
protected void takeDown() {
System.out.println("Destruction de l'agent");
}
#Override
protected void afterMove() {
try {
System.out.println(" La Destination : "
+ this.getContainerController().getContainerName());
} catch (ControllerException e) {
e.printStackTrace();
}
}
}
You don't say nothing about what is the problem with your code. I guess you get at least a compiler message about:
message.setContent(word);
As you access a local variable from an inner class, you must declare the variable as final in the context, like:
final String word = lecteurAvecBuffer.readLine();

Java TextFile Multithreading

I basically want to print all that comes above when i encounter a line
So what i am doing is I am creating a new Thread whenever i encounter a new line. I want to know how to do this. This code below which i wrote is giving wrong outputs i am not able to understand. pls do help
This is the Java code
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
class ThreadDemo extends Thread {
private Thread t;
private String threadName[];
ThreadDemo(String[] name, int le) {
threadName = name;
System.out.println("Creating " + le);
}
public void run() {
// System.out.println("Running " + threadName);
try {
// System.out.println("come");
for (int i = 0; threadName[i] != null; i++) {
System.out.println(i + "y " + threadName[i]);
// Let the thread sleep for a while.
Thread.sleep(0);
}
} catch (InterruptedException e) {
System.out.println("Thread " + threadName + " interrupted.");
}
System.out.println("Thread " + threadName + " exiting.");
}
public void start() {
System.out.println("Starting " + threadName);
if (t == null) {
System.out.println("come");
t = new Thread(this);
t.start();
}
}
}
public class TestThread {
public static void main(String args[]) throws IOException {
FileInputStream input = new FileInputStream("/e:/Amazonsupernew.txt");
PrintWriter output = new PrintWriter("/e:/multicode1.txt");
BufferedReader file = new BufferedReader(new InputStreamReader(input));
Map<String, ArrayList<String>> CusId = new HashMap<String, ArrayList<String>>();
String line;
String[] send = new String[10000];
int i = 0;
while ((line = file.readLine()) != null) {
send[i++] = line;
if (line.isEmpty()) {
send[i - 1] = null;
String temp[] = send;
ThreadDemo T = new ThreadDemo(temp, i);
T.start();
i = 0;
}
}
}
}
File
This is the text file
i just want to print each Ids information each one for each thread

SCTP : java.net.ConnectException: Connection refused

I'm trying to implement a SCTP connection, everything works fine from the server's side but when I run the client program I get the following error:
java.net.ConnectException: Connection refused
at sun.nio.ch.SctpNet.connect0(Native Method)
at sun.nio.ch.SctpNet.connect(SctpNet.java:73)
at sun.nio.ch.SctpChannelImpl.connect(SctpChannelImpl.java:372)
at sun.nio.ch.SctpChannelImpl.connect(SctpChannelImpl.java:438)
at com.sun.nio.sctp.SctpChannel.open(SctpChannel.java:221)
at com.eska.sctp.client.SCTPClient.<init>(SCTPClient.java:20)
at com.eska.sctp.client.SCTPClient.main(SCTPClient.java:62)
The Server Code:
import java.io.IOException;
import java.io.PrintStream;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.util.Iterator;
import com.sun.nio.sctp.AbstractNotificationHandler;
import com.sun.nio.sctp.AssociationChangeNotification;
import com.sun.nio.sctp.AssociationChangeNotification.AssocChangeEvent;
import com.sun.nio.sctp.HandlerResult;
import com.sun.nio.sctp.MessageInfo;
import com.sun.nio.sctp.SctpChannel;
import com.sun.nio.sctp.SctpServerChannel;
import com.sun.nio.sctp.ShutdownNotification;
public class SCTPServer {
private final static int SERVER_PORT = 1111;
private final static int BUFFER_SIZE = 1024;
private SctpServerChannel ssc;
public SCTPServer(int port) throws IOException {
this.ssc = SctpServerChannel.open();
// m.alkhader
// this.ssc.bind(new InetSocketAddress(port));
this.ssc.bind(new InetSocketAddress("127.0.0.1", port));
System.out.println("SCTP server started.");
System.out.println("Local addresses :");
Iterator iterator = this.ssc.getAllLocalAddresses().iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
public void launch() throws IOException {
ByteBuffer buf = ByteBuffer.allocate(BUFFER_SIZE);
CharBuffer cbuf = CharBuffer.allocate(BUFFER_SIZE);
Charset charset = Charset.forName("ISO-8859-1");
CharsetDecoder decoder = charset.newDecoder();
while (true) {
System.out.println("Waiting for client connection...");
SctpChannel sc = this.ssc.accept();
System.out.println("Client connected");
System.out.println("Remote adresses :");
Iterator iterator = sc.getRemoteAddresses().iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
AssociationHandler assocHandler = new AssociationHandler();
MessageInfo messageInfo = null;
do {
buf.clear();
cbuf.clear();
messageInfo = sc.receive(buf, null, assocHandler);
buf.flip();
messageInfo.unordered(true);
if (messageInfo != null && buf.limit() > 0) {
decoder.decode(buf, cbuf, true);
cbuf.flip();
System.out.print("Stream(" + messageInfo.streamNumber()
+ "):");
System.out.println(cbuf);
}
} while (messageInfo != null && buf.limit() > 0);
System.out.println("Connection closed by peer.");
}
}
public static void main(String[] args) {
try {
SCTPServer server = new SCTPServer(SERVER_PORT);
server.launch();
} catch (IOException e) {
System.out.println("Error : " + e.getMessage());
}
}
static class AssociationHandler extends AbstractNotificationHandler {
public HandlerResult handleNotification(
AssociationChangeNotification not, PrintStream stream) {
if (not.event().equals(AssocChangeEvent.COMM_UP)) {
int outbound = not.association().maxOutboundStreams();
int inbound = not.association().maxInboundStreams();
stream.printf("New association setup with %d outbound streams"
+ ", and %d inbound streams.\n", outbound, inbound);
}
return HandlerResult.CONTINUE;
}
public HandlerResult handleNotification(ShutdownNotification not,
PrintStream stream) {
stream.printf("The association has been shutdown.\n");
return HandlerResult.RETURN;
}
}
}
The Client Code:
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.util.Scanner;
import com.sun.nio.sctp.MessageInfo;
import com.sun.nio.sctp.SctpChannel;
public class SCTPClient {
private SctpChannel sc;
private final static int SERVER_PORT = 1111;
private final static int BUFFER_SIZE = 1024;
public SCTPClient(String addr, int port) throws IOException {
this.sc = SctpChannel.open(new InetSocketAddress(addr, port), 0, 0);
}
public void start() throws IOException {
MessageInfo messageInfo = MessageInfo.createOutgoing(null, 0);
Charset charset = Charset.forName("ISO-8859-1");
CharsetEncoder encoder = charset.newEncoder();
ByteBuffer buf = ByteBuffer.allocate(BUFFER_SIZE);
CharBuffer cbuf = CharBuffer.allocate(BUFFER_SIZE);
Scanner scan = new Scanner(System.in);
int i = 0;
int max = this.sc.association().maxInboundStreams();
// messageInfo.unordered(true);
while (scan.hasNext()) {
buf.clear();
cbuf.clear();
cbuf.put(scan.nextLine());
cbuf.flip();
encoder.encode(cbuf, buf, true);
buf.flip();
messageInfo.streamNumber(i % max);
this.sc.send(buf, messageInfo);
i++;
}
}
public void stop() throws IOException {
this.sc.close();
}
public static void main(String[] args) {
try {
System.out.println("Client");
SCTPClient client = new SCTPClient("127.0.0.1", SERVER_PORT);
// SCTPClient client = new SCTPClient("192.168.0.1", SERVER_PORT);
System.out.println("Hello Client");
client.start();
client.stop();
} catch (IOException e) {
System.out.println("Error : " + e.getMessage());
e.printStackTrace();
}
}
}
everything works fine from the server's side

Categories