Errorwhen WriteObject from Server To Socket - java

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.

Related

Filtering request duplicates

I wrote a simple Server:
Server.java:
package com.ltp.server.core;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.ltp.server.core.request.RequestProcessingTask;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
#NoArgsConstructor(access = AccessLevel.PRIVATE)
public class Server {
private static final ExecutorService CLIENTS_POOL = Executors.newFixedThreadPool(100);
private static final Logger LOGGER = LogManager.getLogger(Server.class);
public static void run(final int port) {
try (final ServerSocket serverSocket = new ServerSocket(port)) {
LOGGER.info(String.format("Server started listening on port %d", port));
while (true) {
try {
final Socket client = serverSocket.accept();
CLIENTS_POOL.submit(new RequestProcessingTask(client));
}catch (IOException e) {
LOGGER.error("Unable to read request data");
e.printStackTrace();
}
}
} catch (IOException e) {
LOGGER.fatal("Unable to initialize server");
LOGGER.error(e.getMessage());
}
}
}
RequestProcessingTask.java:
package com.ltp.server.core.request;
import java.net.Socket;
import java.util.concurrent.Callable;
import com.ltp.server.core.request.processor.RequestProcessor;
import com.ltp.server.core.request.processor.RequestReaderProcessor;
import lombok.RequiredArgsConstructor;
#RequiredArgsConstructor
public class RequestProcessingTask implements Callable<Request> {
private final Socket socket;
#Override
public Request call() throws Exception {
final RequestProcessor processorChain = new RequestReaderProcessor();
final Request request = processorChain.process(null, socket);
System.out.println(request.getUrl());
socket.close();
return request;
}
}
I found a problem when started debugging: My browser sends many duplicates of request instead of sending only one. As i understood it is because of browser tries not to lose the request, another words for safety. So can i filter these requests somehow?

SNMP-CAMEL-KAFKA

I am looking for reference where I can get simple program to send a SNMP trap to Apache Kafka topic using Apache Camel.
Please help me if someone can explain the it using simple java program.
My RouteBuilder configuration
import org.apache.camel.builder.RouteBuilder;
public class SimpleRouteBuilder extends RouteBuilder{
#Override
public void configure() throws Exception {
String topicName = "topic=first_topic";
String kafkaServer = "kafka:localhost:9092";
String zooKeeperHost = "zookeeperHost=localhost&zookeeperPort=2181";
String serializerClass = "serializerClass=kafka.serializer.StringEncoder";
String toKafka = new StringBuilder().append(kafkaServer).append("?").append(topicName).append("&")
.append(zooKeeperHost).append("&").append(serializerClass).toString();
System.out.println(toKafka);
from("snmp:127.0.0.1:161?protocol=udp&type=POLL&oids=1.3.6.1.2.1.1.5.0").split().tokenize("\n").to(toKafka);
}
}
Main Method
import org.apache.camel.CamelContext;
import org.apache.camel.impl.DefaultCamelContext;
import org.snmp4j.Snmp;
public class MainApp {
public static void main(String[] args) {
SimpleRouteBuilder routeBuilder = new SimpleRouteBuilder();
CamelContext ctx = new DefaultCamelContext();
try {
ctx.addRoutes(routeBuilder);
ctx.start();
Thread.sleep(5 * 60 * 1000);
ctx.stop();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
I was in wrong direction. The write direction is as below -
Create a Trap sender program.
Create Trap receiver/listener program.
Inside Trap receiver or listener, receive trap and send it to Apache Kafka topic through Apache camel.
POM.XML
add below dependencies -
camel-core
snmp4j
camel-kafka
Trap Sender Program
package <>;
import org.apache.camel.CamelContext;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
import org.snmp4j.*;
import org.snmp4j.event.ResponseEvent;
import org.snmp4j.mp.MPv2c;
import org.snmp4j.mp.MPv3;
import org.snmp4j.mp.SnmpConstants;
import org.snmp4j.security.*;
import org.snmp4j.smi.*;
import org.snmp4j.transport.DefaultUdpTransportMapping;
import java.util.Date;
public class Trapsender {
public static final String community = "public";
public static final String Oid = ".1.3.6.1.2.1.1.8";
public static final String ipAddress = "127.0.0.1";
public static final int port = 162;
public static void main(String[] args) {
Trapsender trapv3 = new Trapsender();
trapv3.sendTrap_Version3();
}
public void sendTrap_Version3() {
try {
// Create Transport Mapping
TransportMapping transport = new DefaultUdpTransportMapping();
transport.listen();
// Create Target
CommunityTarget cTarget = new CommunityTarget();
cTarget.setCommunity(new OctetString(community));
cTarget.setVersion(SnmpConstants.version2c);
cTarget.setAddress(new UdpAddress(ipAddress + "/" + port));
cTarget.setRetries(2);
cTarget.setTimeout(10000);
// Create PDU for V3
PDU pdu = new PDU();
pdu.setType(PDU.TRAP);
// need to specify the system up time
pdu.add(new VariableBinding(SnmpConstants.sysUpTime, new OctetString(new Date().toString())));
pdu.add(new VariableBinding(SnmpConstants.snmpTrapOID, new OID(Oid)));
pdu.add(new VariableBinding(new OID(Oid), new OctetString("Major")));
// Send the PDU
Snmp snmp = new Snmp(transport);
System.out.println("Sending V2 Trap... Check Wheather NMS is Listening or not? ");
ResponseEvent send = snmp.send(pdu, cTarget);
snmp.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Receiver Trap with Apache Camel
package <>;
import org.apache.camel.CamelContext;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.RoutesBuilder;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
import org.snmp4j.*;
import org.snmp4j.mp.MPv1;
import org.snmp4j.mp.MPv2c;
import org.snmp4j.security.Priv3DES;
import org.snmp4j.security.SecurityProtocols;
import org.snmp4j.smi.OctetString;
import org.snmp4j.smi.TcpAddress;
import org.snmp4j.smi.TransportIpAddress;
import org.snmp4j.smi.UdpAddress;
import org.snmp4j.transport.AbstractTransportMapping;
import org.snmp4j.transport.DefaultTcpTransportMapping;
import org.snmp4j.transport.DefaultUdpTransportMapping;
import org.snmp4j.util.MultiThreadedMessageDispatcher;
import org.snmp4j.util.ThreadPool;
import java.io.IOException;
public class Trapreceiver implements CommandResponder {
public static CamelContext ctx=null;
public static ProducerTemplate producer=null;
public static void main(String[] args) {
Trapreceiver snmp4jTrapReceiver = new Trapreceiver();
SimpleRouteBuilder routeBuilder = new SimpleRouteBuilder();
ctx = new DefaultCamelContext();
producer = ctx.createProducerTemplate();
try {
ctx.addRoutes(routeBuilder);
ctx.start();
}
catch (Exception e) {
e.printStackTrace();
}
// producer.sendBody("direct:start", snmp);
try {
snmp4jTrapReceiver.listen(new UdpAddress("localhost/162"), producer);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Trap Listner
*/
public synchronized void listen(TransportIpAddress address, ProducerTemplate producer)
throws IOException {
AbstractTransportMapping transport;
if (address instanceof TcpAddress) {
transport = new DefaultTcpTransportMapping((TcpAddress) address);
} else {
transport = new DefaultUdpTransportMapping((UdpAddress) address);
}
ThreadPool threadPool = ThreadPool.create("DispatcherPool", 10);
MessageDispatcher mDispathcher = new MultiThreadedMessageDispatcher(
threadPool, new MessageDispatcherImpl());
// add message processing models
mDispathcher.addMessageProcessingModel(new MPv1());
mDispathcher.addMessageProcessingModel(new MPv2c());
// add all security protocols
SecurityProtocols.getInstance().addDefaultProtocols();
SecurityProtocols.getInstance().addPrivacyProtocol(new Priv3DES());
// Create Target
CommunityTarget target = new CommunityTarget();
target.setCommunity(new OctetString("public"));
Snmp snmp = new Snmp(mDispathcher, transport);
snmp.addCommandResponder(this);
transport.listen();
System.out.println("Listening on " + address);
try {
this.wait();
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
/**
* This method will be called whenever a pdu is received on the given port
* specified in the listen() method
*/
public synchronized void processPdu(CommandResponderEvent cmdRespEvent) {
System.out.println("Received PDU...");
PDU pdu = cmdRespEvent.getPDU();
if (pdu != null) {
System.out.println("Trap Type = " + pdu.getType());
System.out.println("Variables = " + pdu.getVariableBindings());
producer.sendBody("direct:start","Variables = " + pdu.getVariableBindings() );
}
}
}

The type CalculatorLanguageServer must implement the inherited abstract method StreamConnectionProvider.getErrorStream()

I tried to create the Xtext calculator DSL as guided in the README in this repo. It is an Xtext DSL with a language server and LSP4E implementation, and has 2 sub projects named:
I downloaded the repo and opened it in the Eclipse IDE. Under the main project, there are 2 sub-projects named: org.xtext.calc.parent (which is the xtext project) and org.xtext.calc.lsp4e (the lsp4e implementation project).
In the org.xtext.calc.lsp4e project's src folder there are 3 Java files named: Activator, CalculatorLanguageServer, SocketStreamConnectionProvider. In the latter two, I get an error which I cannot resolve.
Below are the two files: -
1.) CalculatorLanguageServer.java
package org.xtext.calc.lsp4e;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.Platform;
import org.eclipse.lsp4e.server.ProcessStreamConnectionProvider;
import org.eclipse.lsp4e.server.StreamConnectionProvider;
import org.eclipse.lsp4j.jsonrpc.messages.Message;
import org.eclipse.lsp4j.services.LanguageServer;
import org.osgi.framework.Bundle;
public class CalculatorLanguageServer implements StreamConnectionProvider {
private final static boolean SOCKET_MODE = true;
private StreamConnectionProvider delegate;
public CalculatorLanguageServer() {
if (SOCKET_MODE) {
this.delegate = new SocketStreamConnectionProvider(5007) {
};
} else {
List<String> commands = new ArrayList<>();
commands.add("java");
commands.add("-Xdebug");
commands.add("-Xrunjdwp:server=y,transport=dt_socket,address=4001,suspend=n,quiet=y");
commands.add("-jar");
Bundle bundle = Activator.getDefault().getBundle();
URL resource = bundle.getResource("/language-server/calculator-language-server-jar");
try {
commands.add(new File(FileLocator.resolve(resource).toURI()).getAbsolutePath());
} catch (Exception e) {
throw new IllegalStateException(e);
}
this.delegate = new ProcessStreamConnectionProvider(commands, Platform.getLocation().toOSString()) {};
}
}
public void start() throws IOException {
delegate.start();
}
public InputStream getInputStream() {
return delegate.getInputStream();
}
public OutputStream getOutputStream() {
return delegate.getOutputStream();
}
public Object getInitializationOptions(URI rootUri) {
return delegate.getInitializationOptions(rootUri);
}
public void stop() {
delegate.stop();
}
public void handleMessage(Message message, LanguageServer languageServer, URI rootURI) {
delegate.handleMessage(message, languageServer, rootURI);
}
#Override
public String toString() {
return "Calculator Language Server: " + super.toString();
}
}
2.) SocketStreamConnectionProvider.java
package org.xtext.calc.lsp4e;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import org.eclipse.lsp4e.server.StreamConnectionProvider;
public class SocketStreamConnectionProvider implements StreamConnectionProvider {
private int port;
private Socket socket;
private InputStream inputStream;
private OutputStream outputStream;
public SocketStreamConnectionProvider(int port) {
this.port = port;
}
#Override
public void start() throws IOException {
this.socket = new Socket("localhost", port);
inputStream = new BufferedInputStream(socket.getInputStream());
outputStream = new BufferedOutputStream(socket.getOutputStream());
}
#Override
public InputStream getInputStream() {
return inputStream;
}
#Override
public OutputStream getOutputStream() {
return outputStream;
}
#Override
public void stop() {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
In both these files, I get an error in the class names:
1.) The type CalculatorLanguageServer must implement the inherited abstract method StreamConnectionProvider.getErrorStream()
2.) The type SocketStreamConnectionProvider must implement the inherited abstract method StreamConnectionProvider.getErrorStream()
How to resolve these errors?
Thanks!

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 simple Server Client Application Using RUDP in 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.

Categories

Resources