Commit 898f7dc7 authored by Simo Vuorinen's avatar Simo Vuorinen
Browse files

Add new file

parent 642f60e8
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;
public class UDPSender extends Thread {
public static void main(String[] args) throws Exception {
//Muodostetaan TCP-Yhteys
Socket tcpsocket = UDPReceiver();
// Muodostetaan oliovirrat
ObjectInputStream inpStream = new ObjectInputStream(tcpsocket.getInputStream());
ObjectOutputStream outpStream = new ObjectOutputStream(tcpsocket.getOutputStream());
//Lue T - asettaa timeoutin.
tcpsocket.setSoTimeout(5000);
int t= lueT(inpStream, outpStream);
if (t == -1) {
return;
}
for (int i = 0; i <= t; i++ ) {
int p = 5454+i;
outpStream.writeInt(p);
}
for (int i = 0; i <= t; i++ ) {
int p = 5454+i;
ServerSocket uusiSoketti = new ServerSocket(p);
uusiSoketti.setSoTimeout(5000);
Socket soketti = uusiSoketti.accept();
InputStream iS = soketti.getInputStream();
ObjectInputStream oIn = new ObjectInputStream(iS);
int lisattava = 0;
lisattava =lisattava+oIn.readInt();
if ( oIn.readInt()== 0)
break;
}
}
private static Socket UDPReceiver() throws IOException {
int porttiNo = 5454;
int yrityskerta = 0;
ServerSocket pleb = new ServerSocket(porttiNo);
Socket soketti = new Socket();
while (yrityskerta < 5) {
try {
sendUDP(); // lähetetään UDP paketti asiakkaalle
pleb.setSoTimeout(5000); // soketti odottaa yhteydenottoa 5 sek
soketti = pleb.accept();
pleb.close();
System.out.println("TCP muodostettu");
return soketti;
} catch (SocketException e) {
yrityskerta++;
System.out.println("Ei onnistunut");
}
}
return null;
}
private static void sendUDP() {
try {
InetAddress targetAddress = InetAddress.getLoopbackAddress();
DatagramSocket socket = new DatagramSocket(); //luo socketin vapaaseen porttiin paikallisessa koneessa
byte[] data = Integer.toString(5454).getBytes();
DatagramPacket packet = new DatagramPacket (data, data.length, targetAddress, 3126); //luo datagrampacketin
socket.send(packet); // lähettää paketin
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private static int lueT(ObjectInputStream i, ObjectOutputStream o) {
try {
return i.readInt();
} catch (SocketTimeoutException e){
o.writeInt(-1);
return -1;
}
}
}
\ No newline at end of file
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment