package server1;
import java.io.*;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.bluetooth.*;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
import javax.microedition.io.StreamConnectionNotifier;

public class Server {
  public InputStream input;
  public OutputStream output;
  public LocalDevice local=null;
  public DiscoveryAgent agent;
  static String ServiceUrl =
  "btspp://localhost:10203040607040A1B1C1DE100;name=SPP";
  // URL = "btspp://localhost:" + UUID + ";name=rfcommtest;authorize=true";
    public String locaname ;
	public static void main(String[] args) {
           
                       connect();        }
        public static void connect(){
           try {            LocalDevice local = LocalDevice.getLocalDevice();
           local.setDiscoverable(DiscoveryAgent.GIAC);
           DiscoveryAgent agent = local.getDiscoveryAgent();
           String localname = local.getFriendlyName();
          System.out.println("Local address is "+ local.getBluetoothAddress());
             System.out.println("Local name is " + local.getFriendlyName());
        } catch (BluetoothStateException e) {
                 }	try {
            		    // create a server connection
StreamConnectionNotifier notifier =(StreamConnectionNotifier)
        Connector.open(ServiceUrl);
	    // accept client connections
	    StreamConnection connection = notifier.acceptAndOpen();
	    // prepare to send/receive data
            RemoteDevice dev = RemoteDevice.getRemoteDevice(connection);
        System.out.println("Remote device address: "+dev.getBluetoothAddress());
          System.out.println("Remote device name: "+dev.getFriendlyName(true));
           //ByteArrayOutputStream output = new ByteArrayOutputStream();
// Read the data sent from the client until
// the end of stream
          InputStream input = connection.openInputStream();
	  OutputStream output = connection.openOutputStream();
BufferedReader bReader=new BufferedReader(new InputStreamReader(input));
//byte buf[] = new byte[200];
String lineRead=bReader.readLine();
                  System.out.println(lineRead);
                  byte buf[] = lineRead.getBytes();
OutputStream f0 = new FileOutputStream("file1.txt");
for (int i=0; i < buf.length; i ++) {
f0.write(buf[i]);
}
//send response to  client
          PrintWriter pWriter=new PrintWriter(new OutputStreamWriter(output));
          pWriter.write("Response String from SPP Server\r\n");
          pWriter.flush();
          pWriter.close();
                 // streamConnNotifier.close();
// Add the text sent from the client to the Form
//System.out.println(output.toString());
	   		} catch(IOException e) {
				}	}

}
