I am trying to run a simple spp server with android and eclipse and it doesn't seem to be connecting is there competition for the UUID or? Also I am using the MAC address of my computer is that correct?
ConnectTest Code on android
Readout:
...In onCreate()...
...Bluetooth is enabled...
...In onStart()...
...In onResume...
...Attempting client connect...
...Sending Message to server...
Popup:
In onResume() and an exception occured during write: socket closed.
Eclipse sppserver code
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 javax.bluetooth.*;
import javax.microedition.io.*;
/**
* Class that implements an SPP Server which accepts single line of
* message from an SPP client and sends a single line of response to the client.
*/
public class SimpleSPPServer {
//start server
private void startServer() throws IOException{
//Create a UUID for SPP
UUID uuid = new UUID("1101", true);
//Create the servicve url
String connectionString = "btspp://localhost:" + uuid +";name=Sample SPP Server";
//open server url
StreamConnectionNotifier streamConnNotifier = (StreamConnectionNotifier)Connector.open( connectionString );
//Wait for client connection
System.out.println("\nServer Started. Waiting for clients to connect...");
StreamConnection connection=streamConnNotifier.acceptAndOpen();
RemoteDevice dev = RemoteDevice.getRemoteDevice(connection);
System.out.println("Remote device address: "+dev.getBluetoothAddress());
System.out.println("Remote device name: "+dev.getFriendlyName(true));
//read string from spp client
InputStream inStream=connection.openInputStream();
BufferedReader bReader=new BufferedReader(new InputStreamReader(inStream));
String lineRead=bReader.readLine();
System.out.println(lineRead);
//send response to spp client
OutputStream outStream=connection.openOutputStream();
PrintWriter pWriter=new PrintWriter(new OutputStreamWriter(outStream));
pWriter.write("Response String from SPP Server\r\n");
pWriter.flush();
pWriter.close();
streamConnNotifier.close();
}
public static void main(String[] args) throws IOException {
//display local device address and name
LocalDevice localDevice = LocalDevice.getLocalDevice();
System.out.println("Address: "+localDevice.getBluetoothAddress());
System.out.println("Name: "+localDevice.getFriendlyName());
SimpleSPPServer sampleSPPServer=new SimpleSPPServer();
sampleSPPServer.startServer();
}
}
readout:
Address: A45E60EB3CE8
Name: DESKTOP-QD8I9B1
Server Started. Waiting for clients to connect...
Related
I am trying to send message from the android app to the python application in windows but it is not working.
Android app is working good but client created in windows using python is not starting it is showing error that:- Traceback (most recent call last):
File "client.py", line 14, in
s.connect((socket.gethostname(), 9876))
ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it
Here is my client.py file
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import socket
# In[2]:
s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((socket.gethostname(), 9876))
# In[ ]:
while True:
msg = s.recv(1024)
print(msg.decode("utf-8"))
Here is my messageSender.java in android
package com.example.sockets;
import android.os.AsyncTask;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
public class MessegeSender extends AsyncTask<String,Void,Void> {
Socket socket;
DataOutputStream dataOutputStream;
PrintWriter printWriter;
#Override
protected Void doInBackground(String... strings) {
String message=strings[0];
try {
socket = new Socket("192.168.1.6",9876);
printWriter= new PrintWriter(socket.getOutputStream());
printWriter.write(message);
printWriter.flush();
printWriter.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
Here is my Mainactivity.java file in android
package com.example.sockets;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
EditText editText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText=(EditText) findViewById(R.id.msgBox);
}
public void sendMsg(View view)
{
Toast.makeText(this, "Function is running", Toast.LENGTH_SHORT).show();
MessegeSender messegeSender =new MessegeSender();
messegeSender.execute(editText.getText().toString());
}
}
if you want to connect android app to python via sockets then do same as above in android but change the python file by -
#Imports Modules
import socket
import time
listensocket = socket.socket()
Port = 9876
maxConnections = 2
IP = socket.gethostname() #Gets Hostname Of Current Macheine
listensocket.bind(('',Port))
#Opens Server
listensocket.listen(maxConnections)
print("Server started at " + IP + " on port " + str(Port))
#Accepts Incoming Connection
# (clientsocket, address) = listensocket.accept()
# print("New connection made!")
# running = True
#Main
while True:
(clientsocket, address) = listensocket.accept()
message = clientsocket.recv(1024).decode() #Receives Message
print(message) #Prints Message
# if not message == "":
# print(message) #Prints Message
#Closes Server If Message Is Nothing (Client Terminated)
# elif message =="":
# clientsocket.close()
# # running = False
I'm not sure of the exact situation, but if you are trying to connect over the internet you may want to look into this permission, or permissions like this one.
Android has a layer of security which does not allow connections unless the user using application grants the application permission. Look into the permissions for this. My answer may be just a starting point.
<uses-permission android:name="android.permission.INTERNET" />
Here are some resources:
How to add manifest permission to an application?
how to create Socket connection in Android?
Im working on a project that involves sending a string from an android phone to my laptop running a 32 bit windows VM (VMWare Fusion). After doing some searching on how to do such a thing, I get the client (phone) working, but for the server (laptop) end, it never seems to receive anything.
Im sharing bluetooth with the VM, & the device is paired to the host, yet when I send the data it connects to the host, but the VM running the "server" never seems to receive it.
I got the code for the receiver from here, but just for clarifying, heres the code im using for the receiver/server/VM:
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 javax.bluetooth.RemoteDevice;
import javax.bluetooth.UUID;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
import javax.microedition.io.StreamConnectionNotifier;
public class server {
// TODO: Update this to use the window, instead of the console
public void startServer() throws IOException {
// Create a UUID for SPP
UUID uuid = new UUID("1101", true);
//UUID uuid = new UUID("00001101-0000-1000-8000-00805F9B34FB", false);
// Create the servicve url
String connectionString = "btspp://localhost:" + uuid + ";name=SpudSPPServer";
// open server url
StreamConnectionNotifier streamConnNotifier = (StreamConnectionNotifier) Connector.open(connectionString);
// Wait for client connection
System.out.println("\nServer Started. Waiting for clients to connect…");
StreamConnection connection = streamConnNotifier.acceptAndOpen();
RemoteDevice dev = RemoteDevice.getRemoteDevice(connection);
System.out.println("Remote device address: " + dev.getBluetoothAddress());
System.out.println("Remote device name: " + dev.getFriendlyName(true));
// read string from spp client
InputStream inStream = connection.openInputStream();
BufferedReader bReader = new BufferedReader(new InputStreamReader(inStream));
String lineRead = bReader.readLine();
System.out.println(lineRead);
// send response to spp client
OutputStream outStream = connection.openOutputStream();
PrintWriter pWriter = new PrintWriter(new OutputStreamWriter(outStream));
pWriter.write("Response String from SPP Server\r\n");
pWriter.flush();
pWriter.close();
streamConnNotifier.close();
}
}
& in the main file:
public static void main(String args[]) throws IOException {
display d = new display();
server blueToothServer = new server();
d.makePanel();
if (selectFile.fileMissing()) {
d.feed.setText("File missing, creating new file");
selectFile.makeFile();
d.feed.setText("File created! Awaiting data...");
} else {
d.feed.setText("File found! Awaiting data...");
d.MACAddress.setText("MAC Address: " + LocalDevice.getLocalDevice().getBluetoothAddress().replace("-", ":").toUpperCase());
}
blueToothServer.startServer();
}
If you need the code for the client (phone), I can post that if asked
Figured it out, turns out it was on the VMs end, so I just installed windows normally as opposed to a VM, & that fixed it
I'm having trouble interpreting a question for a college assignment. It seems my solution is not an acceptable answer. I'm not looking for the solution just mainly an explanation on what I'm doing wrong.
The question is:
Implement a simple chat client which transmits user messages to a multicast address and receives messages sent from other clients on other machines sent to the same multicast address.
The way I am interpreting this is that I have is a server class with a multicast address, then n-amount of client classes that connect or join the server group.
Then when the client has connected to the server class. The server sends the same typed message out to the multiple clients which is displayed on screen of the client. Am I way off with whats asked??. My code for the multicast server is,
package multicastchatter;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class multicastServer {
final static String INet_addr = "224.0.0.3";
final static int PORT = 8888;
public static void main(String[] args) throws InterruptedException, UnknownHostException {
InetAddress addr = InetAddress.getByName(INet_addr);
try(DatagramSocket serverSocket = new DatagramSocket())//open the datagram
{
for(int i = 0; i<5; i++)
{
String message = "Sent message number "+i;
//create a packet and send
DatagramPacket messPack = new DatagramPacket(message.getBytes(),message.getBytes().length, addr, PORT);
serverSocket.send(messPack);
System.out.println("The server says"+ message);
Thread.sleep(500);
}
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
and my multicast client is
package multicastchatter;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.UnknownHostException;
public class multicastClient {
final static String INet_addr = "224.0.0.3";
final static int PORT = 8888;
//final static int PORT = 8080;
public static void main(String[] args) throws UnknownHostException {
InetAddress address = InetAddress.getByName(INet_addr);//get address
byte[] buf = new byte[256];//create a buffer of bytes
//create the multicast socket
try(MulticastSocket clientSocket = new MulticastSocket(PORT))
{
clientSocket.joinGroup(address);//join the group
while(true)
{//recieve the info
DatagramPacket messPack = new DatagramPacket(buf, buf.length);
clientSocket.receive(messPack);
String message = new String(buf, 0, buf.length);
System.out.println("Socket recieved message saying" + message+ " by "+ messPack.getAddress());
}
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
Any advice is appreciated. All I can think off is that I need to send messages back to the server from the client?
Being that your question is asking if your conceptualization of the client-server architecture is correct, then yes. What your teacher wants is a server that accepts client connections, and broadcasts client messages it receives to all clients.
A multi-threaded server approach is typically chosen in this situation, as many concurrent connections are being utilized, and each of them waits for a message. Upon receiving the message, the server will take that message, append an identifier to the front so that we know what client said the message, and distribute that message once only to each client.
As for the client, it just takes input, sending when necessary, and always listens for packets from the server, displaying whatever it receives. A valuable word of advice:
Do not allow the client side to display what is sent until it is received. In other words, sending input from the client program should only display what was sent when it is received back from the server. It is a good practice to employ in server-client architecture in most instances.
I have a small program where a Server-Client program is getting connected on the same network, but the same program shows a connection time out error in the client program. I have connected the two systems using LAN cable.
Server
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
public class DateServer {
public static void main(String[] args) throws IOException {
ServerSocket listener = new ServerSocket(9090);
try {
while (true) {
Socket socket = listener.accept();
try {
PrintWriter out =
new PrintWriter(socket.getOutputStream(), true);
out.println(new Date().toString());
} finally {
socket.close();
}
}
} finally {
listener.close();
}
}
}
Client
import java.io.BufferedReader;
import java.io.IOException ;
import java.io.InputStreamReader;
import java.net.Socket;
import javax.swing.JOptionPane;
public class DateClient {
public static void main(String[] args) throws IOException {
String serverAddress = JOptionPane.showInputDialog(
"Enter IP Address of a machine that is\n" +
"running the date service on port 9090:");
Socket s = new Socket(serverAddress, 9090);
BufferedReader input =
new BufferedReader(new InputStreamReader(s.getInputStream()));
String answer = input.readLine();
JOptionPane.showMessageDialog(null, answer);
System.exit(0);
}
}
Since the code runs on the same computer, three possibilities come to my mind:
The problem can be either your firewall/access to port rights or having IP addresses as mentioned by other fellows.
You are setting the IP address of the server wrong.
The IP address of the server does not lie on the subnet mask of your network. If you have literaly connected the two computers with a cable (no routers in the middle) you probably haven't setup a DHCP, i.e., your ip addresses should be manually selected. If the ip is selected randomly, chances are your client computer can't find the server computer. try manually setting the ip addresses of both computers to an invalid address within the same subnet mask range and see if it works.
For example set the following addresses:
client IP: 192.168.1.10
subnetmask: 255.255.255.0
server IP: 192.168.1.11
subnetmask: 255.255.255.0
Connecting the two systems with a LAN cable is not sufficient. You have to ensure they have distinct IP addresses, are both in the same IP subnet, and/or have appropriate IP routing tables defined. More typically you would connect both via a router.
is there any small working program for recieving from and sending data to client using java nio.
Actually i am unable to write to socket channel but i am able to read the incoming data
how to write data to socket channel
Thanks
Deepak
You can write data to a socket channel like so:
import java.nio.*;
import java.nio.channels.*;
import java.nio.charset.*;
public class SocketWrite {
public static void main(String[] args) throws Exception{
// create encoder
CharsetEncoder enc = Charset.forName("US-ASCII").newEncoder();
// create socket channel
ServerSocketChannel srv = ServerSocketChannel.open();
// bind channel to port 9001
srv.socket().bind(new java.net.InetSocketAddress(9001));
// make connection
SocketChannel client = srv.accept();
// UNIX line endings
String response = "Hello!\n";
// write encoded data to SocketChannel
client.write(enc.encode(CharBuffer.wrap(response)));
// close connection
client.close();
}
}
The InetSocketAddress may vary depending on what you're connecting to.