How to group 2 udp clients? - java

What i'm trying to do is group 2 clients and make them communicate with eachother. So if 2 clients are connected they would only be able to communicate with eachother and if a third client got connected it would not be able to communicate with the 2 other clients but it would create another group of 2 clients and so on... Right now if a client sends a message it send it over to all clients but i don't know how to make it work like described above. Messages are send from client by typing something in console.
server:
public class Server extends Thread{
public final static int PORT = 7331;
private final static int BUFFER = 1024;
private DatagramSocket socket;
private ArrayList<InetAddress> clientAddresses;
private ArrayList<Integer> clientPorts;
private HashSet<String> existingClients;
public Server() throws IOException {
socket = new DatagramSocket(PORT);
System.out.println("[SERVER] UDP server successfully launched on port " + PORT);
clientAddresses = new ArrayList<InetAddress>();
clientPorts = new ArrayList<Integer>();
existingClients = new HashSet<String>();
}
public void run() {
byte[] buf = new byte[BUFFER];
while (true) {
try {
//resets buffer so only new messages get displayed
Arrays.fill(buf, (byte) 0);
DatagramPacket packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
String content = new String(buf, buf.length);
InetAddress clientAddress = packet.getAddress();
int clientPort = packet.getPort();
String id = clientAddress.toString() + "," + clientPort;
if (!existingClients.contains(id)) {
existingClients.add(id);
clientPorts.add(clientPort);
clientAddresses.add(clientAddress);
}
System.out.println(id + " : " + content);
byte[] data = (id + " : " + content).getBytes();
for (int i = 0; i < clientAddresses.size(); i++) {
InetAddress cl = clientAddresses.get(i);
int cp = clientPorts.get(i);
packet = new DatagramPacket(data, data.length, cl, cp);
socket.send(packet);
}
} catch (Exception e) {
System.err.println(e);
}
}
}
public static void main(String args[]) throws Exception {
Server s = new Server();
s.start();
}
}
clients:
public class Client implements Runnable {
public static void main(String args[]) throws Exception {
String host = "127.0.0.1";
DatagramSocket socket = new DatagramSocket();
//handles the receiving part for every client (incoming packets to clients)
MessageReceiver r = new MessageReceiver(socket);
Client s = new Client(socket, host);
Thread rt = new Thread(r);
Thread st = new Thread(s);
rt.start();
st.start();
}
public final static int PORT = 7331;
private DatagramSocket sock;
private String hostname;
Client(DatagramSocket s, String h) {
sock = s;
hostname = h;
}
//sending clients socket to server
private void sendMessage(String s) throws Exception {
//getting bytes from message
byte buf[] = s.getBytes();
//getting hostname from server
InetAddress address = InetAddress.getByName(hostname);
//setting up packet
DatagramPacket packet = new DatagramPacket(buf, buf.length, address, PORT);
//sending packet to server
sock.send(packet);
}
public void run() {
//connected boolean is used to send a greetings message once for every new client that has joined
boolean connected = false;
do {
try {
sendMessage("GREETINGS");
connected = true;
} catch (Exception e) {
}
} while (!connected);
//reads from the console
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
while (true) {
try {
while (!in.ready()) {
Thread.sleep(100);
}
//sends message from console to server
sendMessage(in.readLine());
} catch (Exception e) {
System.err.println(e);
}
}
}
}
//this class handles receiving part of clients
class MessageReceiver implements Runnable {
DatagramSocket sock;
byte buf[];
MessageReceiver(DatagramSocket s) {
sock = s;
buf = new byte[1024];
}
public void run() {
while (true) {
try {
DatagramPacket packet = new DatagramPacket(buf, buf.length);
sock.receive(packet);
String received = new String(packet.getData(), 0,
packet.getLength());
System.out.println(received);
} catch (Exception e) {
System.err.println(e);
}
}
}
}

What youre trying is a message broadcast or a message-repeater-client.
broadcasting is implemented on network layer (using brodcast the local network broadcast adress).
And if you implementing it that way, you'll flood your network, when you have more than 2 clients. Best regards to your network admin. ;-)

Related

How to send messages between two UDP clients?

What i'm trying to do is group 2 clients and make them communicate with eachother. So if 2 clients are connected they would only be able to communicate with eachother and if a third client got connected it would not be able to communicate with the 2 other clients but it would create another group of 2 clients and so on... Right now if a client sends a message it send it over to all clients but i'm not sure how to make them communicate in groups of 2 like in a peer-to-peer connection.
class Server {
private static DatagramSocket socket = null;
private static Map<Session, Integer> sessions = new HashMap<Session, Integer>();
private static Session session = new Session();
public static void main(String[] args) {
try {
socket = new DatagramSocket(6066);
} catch (SocketException e) {
System.out.println("[SERVER] Unable to launch server on port: " + socket.getLocalPort());
}
System.out.println("[SERVER] Server launched successfully on port " + socket.getLocalPort());
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
byte[] buffer = new byte[100];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
while (true) {
Arrays.fill(buffer, (byte) 0);
try {
socket.receive(packet);
} catch (IOException e) {
System.out.println("[SERVER] Unable to receive packets from buffer");
}
InetAddress ip = packet.getAddress();
int port = packet.getPort();
String data = new String(packet.getData()).trim();
if(session.getIp1() == null) {
session.setIp1(ip);
session.setPort1(port);
session.setData1(data);
} else {
session.setIp2(ip);
session.setPort2(port);
session.setData2(data);
}
DatagramPacket pt = new DatagramPacket(packet.getData(), packet.getData().length, ip, port);
try {
socket.send(pt);
} catch (IOException e) {
System.out.println("[SERVER] Unable to send packets to client.");
}
}
}
});
thread.start();
}
}
Client:
public class Client {
private static DatagramSocket socket = null;
public static void main(String[] args) {
System.out.println("Send to server:");
Scanner scanner = new Scanner(System.in);
while (true) {
try {
// port shoudn't be the same as in TCP but the port in the datagram packet must
// be the same!
socket = new DatagramSocket();
} catch (SocketException e1) {
System.out.println("[CLIENT] Unable to initiate DatagramSocket");
}
InetAddress ip = null;
try {
ip = InetAddress.getByName("127.0.0.1");
} catch (UnknownHostException e) {
System.out.println("[CLIENT] Unable to determine server IP");
}
// must be in a while loop so we can continuously send messages to server
String message = null;
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
receive();
}
});
thread.start();
while (scanner.hasNextLine()) {
message = scanner.nextLine();
byte[] buffer = message.getBytes();
DatagramPacket packet = new DatagramPacket(buffer, buffer.length, ip, 6066);
try {
socket.send(packet);
} catch (IOException e) {
System.out.println("[CLIENT] Unable to send packet to server");
}
}
}
}
private static void receive() {
// receiving from server
byte[] buffer2 = new byte[100];
DatagramPacket ps = new DatagramPacket(buffer2, buffer2.length);
while (true) {
try {
socket.receive(ps);
} catch (IOException e) {
System.out.println("[CLIENT] Unable to receive packets from server.");
}
System.out.println("[SERVER] " + new String(ps.getData()));
}
}
}
Object class:
public class Session {
private InetAddress ip1;
private int port1;
private String data1;
private InetAddress ip2;
private int port2;
private String data2;
public Session() {
}
public InetAddress getIp1() {
return ip1;
}
public void setIp1(InetAddress ip1) {
this.ip1 = ip1;
}
public int getPort1() {
return port1;
}
public void setPort1(int port1) {
this.port1 = port1;
}
public String getData1() {
return data1;
}
public void setData1(String data1) {
this.data1 = data1;
}
public InetAddress getIp2() {
return ip2;
}
public void setIp2(InetAddress ip2) {
this.ip2 = ip2;
}
public int getPort2() {
return port2;
}
public void setPort2(int port2) {
this.port2 = port2;
}
public String getData2() {
return data2;
}
public void setData2(String data2) {
this.data2 = data2;
}
}
Currently, you store the client's information in an array. Make an object where it will contain two client session's data. When a new client is attempting to connect, see if there are any objects that have a free spot, if not, create a new object and await a new participant; otherwise, join an existing session.
Hackish way: Create a Map<ObjectHere, UserCount> then filter based on userCounts = 1 and then join the session to the first returned Object.

Why is my server socket not receiving packet sent by the client

I want to create a datagram server/client program where the server picks a random string from an array and send it to the client. But when i run the server and then the client which sends data about the buf byte array. The client sends the data to the serve as I understand but the server doesn't receive it.
Here's the client code:
import java.io.*;
import java.net.*;
import java.util.*;
public class SDClient {
protected static String labelText;
public static void main(String[] args) throws IOException {
//socket setup
MulticastSocket socket = new MulticastSocket(1);
System.out.println("socket opened");
InetAddress group = InetAddress.getByName("230.0.0.0");
socket.joinGroup(group);
System.out.println("socket joined group");
//packet setup
DatagramPacket packet;
byte[] buf = new byte[256];
//send packet
packet = new DatagramPacket(buf, buf.length);
packet.setAddress(group);
packet.setPort(2);
socket.send(packet);
System.out.println("packet sent to: ");
System.out.println("Port: " + packet.getPort() + " Address: " + packet.getAddress());
//receive packet
packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
System.out.println("packet received");
//display packet string
labelText = new String(packet.getData(), 0, packet.getLength());
System.out.println("label text: " + labelText);
socket.leaveGroup(group);
socket.close();
}
}
here's the server code:
import java.io.*;
import java.net.*;
import java.util.*;
public class SDServerThread extends Thread {
protected DatagramSocket socket = null;
protected String[] labelText = {"Packet sent and received", "Hello World!", "It works."};
public SDServerThread() throws IOException {
this("SDServerThread");
}
public SDServerThread(String name) throws IOException {
super(name);
socket = new DatagramSocket(2);
System.out.println("socket opened");
}
public void run() {
try {
byte[] buf = new byte[256];
DatagramPacket packet = null;
packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
System.out.println("packet received");
String getText = getText();
buf = getText.getBytes();
InetAddress group = InetAddress.getByName("230.0.0.0");
packet = new DatagramPacket(buf, buf.length, group, 1);
socket.send(packet);
System.out.println("packet sent");
} catch (IOException e) {
e.printStackTrace();
}
}
private String getText() {
int textNr = (int)(Math.random() * 3);
String returnT = labelText[textNr];
return returnT;
}
}
Thanks in advence
I fixed it by making the servers DatagramSocket into a MulticastSocket and then made it join the group the client is in.
public class SDServerThread extends Thread {
protected MulticastSocket socket = null;
...
socket = new MulticastSocket(2);
...
socket.joinGroup(group);
}

Java DatagramSocket doesn't receive data

I'm writing a simple client / server in java and I got this problem that I cannot fix.
I'm using DatagramSocket on both client and server and my server just cannot receive any data. I don't get any errors but it just doesn't work.
Here is my source code for server:
public class GameServer {
public static final String serverBuild = "0.00 (050319.milestone0-main)";
public static final String protocolBuild = "1";
public DatagramSocket serverSocket;
public boolean isRunning = false;
public Thread clientHandler;
public GameServer(int port, String serverName) {
System.out.println("Server> Starting a server on port: " + port + ".");
System.out.println("Server> " + serverName + " running on server build " + serverBuild + ".");
System.out.println("Server> Using protocol ID: " + protocolBuild + ".");
isRunning = true;
try {
serverSocket = new DatagramSocket(port);
}catch(Exception ex) {
System.out.print("Server> ");
ex.printStackTrace();
}
clientHandler();
}
public void clientHandler() {
clientHandler = new Thread(new Runnable() {
public void run() {
while(isRunning) {
byte[] buffer = new byte[256];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
try {
serverSocket.receive(packet);
System.out.println("Server> " + new String(packet.getData(), 0, packet.getData().length));
} catch (IOException e) {
System.out.print("Server> ");
e.printStackTrace();
}
}
}
});
clientHandler.start();
}
}
Here is my source code for client:
public class GameClient {
public GameClient() {
try {
DatagramSocket socket = new DatagramSocket(25567);
byte[] buffer = new byte[256];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length, InetAddress.getByName("192.168.0.24"), 25567);
socket.send(packet);
}catch(Exception ex) {
ex.printStackTrace();
}
}
}
Client is very simple because I was looking why my server doesn't work.
The console does not print anything, because the client sends the package is an empty array. The server is work right.

Bind Exception when trying to send UDP packet

I am making a peer to peer chat application for which I have written the below code for chat with one person. This code works for localhost(127.0.0.1) but doesn't work for any specific ip address(192.168.43.118) and throws bindexception. Please help.
import java.sql.*;
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class communicate {
public static void main(String args[]) throws Exception {
communicate ob = new communicate();
String ip = "192.168.43.118";
ob.text(ip);
}
public void text(String friend_ip) throws Exception{
System.out.println("Press 'Exit' to exit the chat");
int send_port = 40002;
int receive_port = 40002;
//InetAddress inetaddr = InetAddress.getByName(friend_ip);
byte[] ipAddr = new byte[] { (byte)192, (byte)168, (byte)43, (byte)118 };
System.out.println(ipAddr.length);
InetAddress inetaddr = InetAddress.getByAddress(ipAddr);
System.out.println("B");
DatagramSocket serverSocket = new DatagramSocket(receive_port, inetaddr);
System.out.println("YO");
Runnable send = new SendMsg(send_port, friend_ip, serverSocket);
Runnable receive = new GetMsg(friend_ip, receive_port, serverSocket);
Thread t1 = new Thread(send);
Thread t2 = new Thread(receive);
t1.start();
t2.start();
}
class SendMsg implements Runnable {
private DatagramSocket senderSocket;
private int send_port;
private String sendto_ip;
SendMsg(int port, String friend_ip, DatagramSocket ds)throws Exception {
senderSocket = new DatagramSocket(64432);
send_port = port;
sendto_ip = friend_ip;
}
public void run(){
try {
while(true) {
String sendString;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
sendString = br.readLine();
byte[] sendData = sendString.getBytes();
byte[] ipAddr = new byte[] { (byte)192, (byte)168, (byte)43, (byte)118 };
InetAddress inetAddress = InetAddress.getByAddress(ipAddr);
DatagramPacket sendPacket = new DatagramPacket (sendData, sendData.length, inetAddress, send_port);
senderSocket.send(sendPacket);
System.out.println("Message Sent");
}
}
catch(Exception e) {
System.out.println("Exc at Sender\n" + e);
}
finally {
if(senderSocket != null) senderSocket.close();
}
}
}
class GetMsg implements Runnable{
private DatagramSocket serverSocket;
private String friend_ip;
private int receive_port;
GetMsg(String ip, int port, DatagramSocket ds) throws Exception{
friend_ip = ip;
receive_port = port;
serverSocket = ds;
}
public void run(){
try {
while(true) {
byte[] receiveData = new byte[10000];
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
String message = new String (receivePacket.getData(), 0, receivePacket.getLength());
System.out.println(friend_ip + ": " + message);
}
}
catch(Exception e) {
System.out.println("Exc at Rec\n" + e);
}
finally {
if(serverSocket != null) serverSocket.close();
}
}
}
}
When I run it on terminal the following output is shown
Press 'Exit' to exit the chat
4
B
Exception in thread "main" java.net.BindException: Cannot assign requested address (Bind failed)
at java.base/java.net.PlainDatagramSocketImpl.bind0(Native Method)
at java.base/java.net.AbstractPlainDatagramSocketImpl.bind(AbstractPlainDatagramSocketImpl.java:131)
at java.base/java.net.DatagramSocket.bind(DatagramSocket.java:394)
at java.base/java.net.DatagramSocket.<init>(DatagramSocket.java:244)
at java.base/java.net.DatagramSocket.<init>(DatagramSocket.java:301)
at communicate.text(communicate.java:21)
at communicate.main(communicate.java:10)
As "YO" is not printed it seems that error is in the text method where I am trying to create DatagramSocket. Where am I going wrong?
If you want read, do not bind the remote address. Just create a local UDP socket (it will be a server socket) and just read from/write to its buffer. You can bind to your local network interface only and these must be initialized before. So you cannot bind to an unused Wifi, or unplugged ethernet adapter.
If you want test a sender, and a receiver in the same java program on different threads, you have to use two different socket.
A hint: use InetAddress.getByName(IPv4) for string IP input, you do not need the byte array.

java.net.BindException: EADDRINUSE (Address already in use)

I'm trying to connect and transfer data through Wifi-Direct on Android phones. What I've basically done in my P2PConnectionManager.java file is -
Created a connection to the peer through the P2pManager
Called the class ServerHandshake if I am the Group Owner
Called the class ClientHandshake if I am not the GroupOwner
in these two classes I have exchanged the IP addresses and MAC addresses of the phones (this I've done to enable communication with multiple phones). I have used Datagram Sockets everywhere as that is what is required right now for what I am trying to do.
In P2PSend.java, once I select the file, I have tried to send it over a DatagramSocket as well, but it is giving me a bind failed: EADDRINUSE (Address already in use) exception.
I am using different ports for both the connections, and even included socket.setReuseAddress()
Can someone please point out where I am going wrong? I apologize for the mess in the code.
P2PConnectionManager.java:
public void onConnectionInfoAvailable(WifiP2pInfo info) {
//here check whether we're the group owner, then create server socket if so
if(info.isGroupOwner){
appendToConsole("CMGR: Setting up server handshake on " + info.groupOwnerAddress.getHostAddress() + ":5555");
//setup the server handshake with the group's IP, port, the device's mac, and the port for the conenction to communicate on
ServerHandshake sh = new ServerHandshake();
sh.setup(myMAC, info.groupOwnerAddress.getHostAddress(),5555,childportstart);
childportstart += 2;
sh.execute();
}else{
//give server a second to setup the server socket
try{
Thread.sleep(1000);
}catch (Exception e){
System.out.println(e.toString());
}
String myIP = "";
try {
Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
while(en.hasMoreElements()){
NetworkInterface ni = en.nextElement();
Enumeration<InetAddress> en2 = ni.getInetAddresses();
while(en2.hasMoreElements()){
InetAddress inet = en2.nextElement();
if(!inet.isLoopbackAddress() && inet instanceof Inet4Address){
myIP = inet.getHostAddress();
}
}
}
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
appendToConsole("CMGR: Setting up client handshake from " + myIP + ":5555");
//setup the client handshake to connect to the server and trasfer the device's MAC, get port for connection's communication
ClientHandshake ch = new ClientHandshake();
ch.setup(info.groupOwnerAddress.getHostAddress(),5555,myMAC,myIP);
ch.execute();
}
}
ClientHandshake class:
public class ClientHandshake extends AsyncTask<Void, Void, String> {
String peerIP;
String peerMAC;
int peerPort;
int childport;
byte[] buffer;
byte[] buffer2;
DatagramSocket clientSocket;
OutputStream outs;
InputStream ins;
String myMAC;
String myIP;
public void setup(String peerIP, int peerPort, String myMAC, String myIP ) {
this.peerIP = peerIP;
this.peerPort = peerPort;
this.myMAC = myMAC;
this.myIP = myIP;
}
public String doInBackground(Void...params) {
try{
clientSocket = new DatagramSocket(peerPort);
clientSocket.setReuseAddress(true);
System.out.println("Peerport: " + peerPort);
InetAddress IPAddress = InetAddress.getByName(peerIP);
System.out.println("CH: PEERIP ADDRESS - " + IPAddress);
int len = myIP.length();
byte[] sendMyMac = new byte[17];
byte[] sendMyIPlen = new byte[2];
byte[] sendMyIP = new byte[len];
byte[] receivePeerMAC = new byte[17];
byte[] receivePort = new byte[4];
//write our MAC address
sendMyMac = myMAC.getBytes();
System.out.println("myMAC - " + myMAC);
DatagramPacket sendPacket1 = new DatagramPacket(sendMyMac, sendMyMac.length, IPAddress, peerPort);
clientSocket.send(sendPacket1);
System.out.println("sendMyMAC done -");
//write our IP add len
String string = String.valueOf(myIP.length());
sendMyIPlen = string.getBytes();
System.out.println("myIPlen - " + myIP.length());
DatagramPacket sendPacket2 = new DatagramPacket(sendMyIPlen, sendMyIPlen.length, IPAddress, peerPort);
clientSocket.send(sendPacket2);
System.out.println("sendMyIPlen done -");
//write our IP add
sendMyIP = myIP.getBytes();
System.out.println("myIP - " + myIP);
DatagramPacket sendPacket3 = new DatagramPacket(sendMyIP, sendMyIP.length, IPAddress, peerPort);
clientSocket.send(sendPacket3);
System.out.println("SendMyIP done -");
//read peer's MAC address
DatagramPacket receivePeerMac = new DatagramPacket(receivePeerMAC, receivePeerMAC.length);
clientSocket.receive(receivePeerMac);
String peerMAC = new String(receivePeerMac.getData());
System.out.println("FROM SERVER:" + peerMAC);
//read the port
DatagramPacket port = new DatagramPacket(receivePort, receivePort.length);
clientSocket.receive(port);
String cport = new String (port.getData());
int childport = Integer.parseInt(cport);
clientSocket.close();
return peerMAC;
}catch(Exception e){
e.printStackTrace();
}
return null;
}
#Override
public void onPostExecute(String peerMAC){
createNewP2PConnection(myMAC,myIP,peerMAC,peerIP,childport,0);
}
}
ServerHandshake class:
public class ServerHandshake extends AsyncTask<Void, Void, String> {
int portno;
int childport;
int peerIPlen;
byte[] buffer;
byte[] buffer2;
Socket s;
DatagramSocket serverSocket;
InputStream ins;
OutputStream outs;
String myMAC;
String myIP;
String ipaddr;
String peerMAC;
String peerIP;
int myPort;
public void setup(String myMAC, String myIP, int myPort, int childport) {
this.myIP = myIP;
this.myMAC = myMAC;
this.myPort = myPort;
this.childport = childport;
}
public String doInBackground(Void...params) {
System.out.println("Checking SH");
System.out.println("CP : "+childport);
try{
serverSocket = new DatagramSocket(5555);
serverSocket.setReuseAddress(true);
//serverSocket.setSoTimeout(5000);
byte[] receivePeerMAC = new byte[17];
byte[] receivePeerIPlen = new byte[2];
byte[] sendMyMac = new byte[17];
byte[] sendMyPort = new byte[4];
try {
Thread.sleep(5000);
}catch(Exception e) {
e.printStackTrace();
}
//read Peer Mac
DatagramPacket PeerMac = new DatagramPacket(receivePeerMAC, receivePeerMAC.length);
serverSocket.receive(PeerMac);
String peerMAC = new String(PeerMac.getData());
System.out.println("RECEIVEDpeerMAC: " + peerMAC);
InetAddress IPAddress = PeerMac.getAddress();
int port = PeerMac.getPort();
//read peer IP's len
DatagramPacket IPlen = new DatagramPacket(receivePeerIPlen, receivePeerIPlen.length);
serverSocket.receive(IPlen);
String PeerIPlen = new String(IPlen.getData());
int peerIPlen = Integer.parseInt(PeerIPlen);
System.out.println("RECEIVEDpeerIPlenstring: " + PeerIPlen + " .... int: " + peerIPlen + "ANY DIFFERENCE??");
//read peer IP
byte [] receivePeerIP = new byte [peerIPlen];
DatagramPacket IP = new DatagramPacket(receivePeerIP, receivePeerIP.length);
serverSocket.receive(IP);
String peerIP = new String(IP.getData());
System.out.println("RECEIVEDpeerIP: " + peerIP);
//Write our local MAC
sendMyMac = myMAC.getBytes();
System.out.println("myMAC - " + myMAC);
DatagramPacket sendPacket1 = new DatagramPacket(sendMyMac, sendMyMac.length, IPAddress, port);
serverSocket.send(sendPacket1);
System.out.println("sendMyMAC done -");
//Write the port to talk on
String string = String.valueOf(childport);
sendMyPort = string.getBytes();
DatagramPacket sendPacket2 = new DatagramPacket(sendMyPort, sendMyPort.length, IPAddress, port);
serverSocket.send(sendPacket2);
System.out.println("Port: " + childport);
serverSocket.close();
return (peerIP);
}catch(Exception e){
e.printStackTrace();
}
return (null);
}
public void onPostExecute(String peerIP){ //changed from (String peerMAC)
createNewP2PConnection(myMAC,myIP,peerMAC,peerIP,childport,1);
}
}
P2PSend.java:
Note: I have used IntentService here, just to get the filepath, destination IP and port
public class P2PSend extends IntentService {
private static final int SOCKET_TIMEOUT = 15000;
public static final String ACTION_SEND_FILE = "com.p2pwifidirect.connectionmanager.SEND_FILE";
public static final String EXTRAS_FILE_PATH = "file_url";
public static final String EXTRAS_DESTINATION = "go_host";
public static final String EXTRAS_DESTINATION_PORT = "go_port";
public static final String EXTRAS_MY_IP = "my_ip";
public P2PSend() {
super("P2PSend");
System.out.println("P2PSend.java started IntentService");
}
protected void onHandleIntent(Intent intent) {
System.out.println("P2PSend.java started onHandleIntent");
Context context = getApplicationContext();
System.out.println("Intent: " + intent);
String fileUri = intent.getExtras().getString(EXTRAS_FILE_PATH);
String host = intent.getExtras().getString(EXTRAS_DESTINATION); //this is the IP address of the receiver
String myIP = intent.getExtras().getString(EXTRAS_MY_IP); //my IP address
System.out.println("P2PSend:Host Address: " + host);
//int port = intent.getExtras().getInt(EXTRAS_DESTINATION_PORT);
int port = 6000;
System.out.println("P2PSend:Port: " + port);
System.out.println("P2PSend:fileUri: " + fileUri);
try {
DatagramSocket socket = new DatagramSocket(port);
System.out.println("Opening client socket - ");
//socket.bind(new InetSocketAddress(myIP, port));
InetAddress hostAddress = InetAddress.getByName(host);
socket.connect(new InetSocketAddress(hostAddress, port));
//socket.setSoTimeout(SOCKET_TIMEOUT); //is it needed???
System.out.println("Client socket - " + socket.isConnected());
ContentResolver cr = context.getContentResolver();
InputStream is = null;
is = cr.openInputStream(Uri.parse(fileUri));
byte buf[] = new byte[1024];
int len = 0;
while ((len = is.read(buf)) != -1) {
DatagramPacket packet = new DatagramPacket(buf,buf.length, hostAddress, port);
//System.out.println("Client socket - " + socket.isConnected());
socket.send(packet);
System.out.println("Writing data: " + packet);
System.out.println("Writing data now...");
}
is.close();
if (socket != null) {
if (socket.isConnected()) {
try {
socket.close();
} catch (Exception e) {
// Give up
e.printStackTrace();
}
}
}
} catch (Exception e) {
System.out.println(e.toString());
}
System.out.println("Client: Data written");
}
Any suggestions as to where I'm going wrong?
Thank you so much!
Create the socket this way:
clientSocket = new DatagramSocket();
clientSocket.setReuseAddress(true);
clientSocket.bind(new InetSocketAddress(peerPort));
If you want to send Broadcast, also consider adding this line before binding it:
clientSocket.setBroadcast(true);

Categories