7 Temmuz 2009 Salı

Java da soket programlama

// Serialization example.
2 // Derived by Hadi from previous DateServer.java
3 import java.util.Date;
4 import java.net.*;
5 import java.io.*;
6 public class DateServer {
7 public static void main (String [] args) {
8 try {
9 DateServer world = new DateServer();
10 } catch (IOException e) {
11 System.out.println("IO exception " + e);
12 }
13 }
14 static final public int portNumber = 4291;
15 public DateServer () throws IOException {
16 ServerSocket server = new ServerSocket(portNumber);
17 while (true) {
18 System.out.println("Waiting for a client");
19 Socket sock = server.accept();
20 System.out.println("Got a client, send a message");
21 ObjectOutputStream out = new ObjectOutputStream(sock.getOutputStream());
22
23 out.writeObject(new Date());
24 }
25 }
26 }


===============================================================================
===============================================================================
===============================================================================


1 import java.net.*;
2 import java.io.*;
3 public class DateClient {
4 public static void main (String [] args) {
5 try {
6 DateClient world = new DateClient();
7 } catch (IOException e) {
8 System.out.println("Received an IO exception " + e);
9 }
10 }
11 static final public int portNumber = 4291;
12 public DateClient () throws IOException {
13 Socket sock = new Socket(InetAddress.getLocalHost(), portNumber);
14 Reader isread = new InputStreamReader(sock.getInputStream());
15 BufferedReader input = new BufferedReader(isread);
16 System.out.println("message is " + input.readLine());
17 }
18 }


===============================================================================
===============================================================================
===============================================================================


1 import java.net.*;
2 import java.io.*;
3 class Therapist {
4 static public void main (String [ ] args) {
5 try {
6 Therapist world = new Therapist();
7 } catch (IOException e) {
8 System.out.println("Received an IO Exception" + e);
9 }
10 }
11 static final public int portNumber = 5321;
12 public Therapist () throws IOException {
13 ServerSocket server = new ServerSocket(portNumber);
14 while (true) {
15 Socket sock = server.accept();
16 Thread session = new TherapySession
17 (sock.getInputStream(), sock.getOutputStream());
18 session.start();
19 }
20 }
21 }

===============================================================================
===============================================================================
===============================================================================


1 import java.io.*;
2 import java.util.Vector;
3 import java.util.StringTokenizer;
4 class TherapySession extends Thread {
5 public TherapySession (InputStream ins, OutputStream outs) {
6 Reader isread = new InputStreamReader(ins);
7 in = new BufferedReader(isread);
8 out = new OutputStreamWriter(outs);
9 }
10 private String name = "";
11 private BufferedReader in;
12 private Writer out;
13 private String response(String text) {
14 // answer a question with a question
15 if (text.endsWith("?"))
16 return "Why do you want to know?";
17 // break up line
18 Vector words = new Vector();
19 StringTokenizer breaker = new StringTokenizer(text, " .,?!");
20 while (breaker.hasMoreElements())
21 words.addElement(breaker.nextElement());
22 // look for ``I feel''
23 if ((words.size() > 1) &&
24 words.elementAt(0).equals("i") &&
25 words.elementAt(1).equals("feel"))
26 return "Why do you feel that way?";
27 // look for relatives
28 for (int i = 0; i < words.size(); i++) {
29 String relative = (String) words.elementAt(i);
30 if (isRelative(relative))
31 return "Tell me more about your " + relative;
32 }
33 // nothing else, generic response
34 return "Tell me more";
35 }
36 private boolean isRelative(String name) {
37 return name.equals("mother") || name.equals("father")
38 || name.equals("brother") || name.equals("sister")
39 || name.equals("uncle");
40 }
41
42 public void run() {
43 try {
44 // get name
45 out.write("Hello. Welcome to therapy. What is your name?\n");
46 out.flush();
47 name = in.readLine();
48 out.write("Well " + name + " what can we do for you today?\n");
49 out.flush();
50 // now read and respond
51 while (true) {
52 String text = in.readLine();
53 out.write(response(text) + "\n");
54 out.flush();
55 }
56 } catch (IOException e) { stop(); }
57 }
58 }



===============================================================================
===============================================================================
===============================================================================



1 import java.io.*;
2 import java.net.*;
3 class TherapyClient {
4 public static void main (String [ ] args) {
5 try {
6 TherapyClient world = new TherapyClient();
7 } catch (IOException e) {
8 System.out.println("got IO exception " + e);
9 }
10 }
11 static final public int portNumber = 5321;
12 private BufferedReader input, term;
13 private Writer output;
14 public TherapyClient () throws IOException {
15 // open standard input as buffered reader
16 term = new BufferedReader(new InputStreamReader(System.in));
17 // open socket as a reader and a writer
18 Socket sock = new Socket(InetAddress.getLocalHost(), portNumber);
19 Reader isread = new InputStreamReader(sock.getInputStream());
20 input = new BufferedReader(isread);
21 output = new OutputStreamWriter(sock.getOutputStream());
22 // now read and print
23 while (true) {
24 // read and print something from therapist
25 String line = input.readLine();
26 System.out.println(line);
27 // get our response
28 line = term.readLine();
29 if (line.equals("Quit"))
30 break;
31 output.write(line + "\n");
32 output.flush();
33 }
34 }
35 }

Ağ Üzerinden Nesne Aktarımı

Nesnelerin ağ üzerinden aktarılması nesne dizileştirme (object serialization) yötemiyle mümkündür. Nesne dizileştirme metodu çalışma esnasında üretilen herhangibir nesnenin o anki durumunu saklamak ve bir dahaki işletimde kalınan yeerden devam etmek gibi amaçlarla da kullanılmaktadır. Burada yapılan sadece nesneyi, diske veya ağ üzerinden karşı tarafa aktarabilecek şekilde karakter dizilerine çevirmektir. Sonra aynı işlemin tersi (unserialization) yapılarak diskten veya ağ üzerinden okunan karakter dizileri programın kullanabileceği nesneler haline getirilir.

Örnek olarak daha önce verilen 'DateServer.java' ve 'DateClient.java' uygulaması biraz değiştirilerek sunucunun verdiği zamanın istemcinin çalıştığı makinanın yerel zaman formatında gösterilmesini sağlandı.

Sunucu tarafında (DateServer.java), çıkış akımı (stream), 'ObjectOutputStream' türü bir nesne olarak açılarak sistem zamanını gösteren 'Date' türü nesnemiz 'writeObject' metoduyla bu akıma verildi. Bu fonksiyon içinde nesne dizileştirilerek ağ üzerinden karşı makineye gönderilir.

İstemci tarafında (DateClient.java) ise giriş akımı (stream), 'ObjectInputStream' türü bir nesne olarak açılır ve 'readObject' metodu kullanılarak soketin giriş akımı üzerinden, gönderilen dizi alınır ve tekrar nesne haline getirilir. Sonra da nesnenin yerel makinadaki karşılığı 'String' olarak alınarak ekrana basılır.

http://www.godoro.com/divisions/ehil/mecmua/Magazines/Articles/txt/html/article_JavaNetworkProgramming.html

6 Temmuz 2009 Pazartesi

Bluetooth Java

import java.util.*;

import java.io.*;
import javax.microedition.io.*;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.bluetooth.*;
import javax.obex.*;

public class BluetoothGPSMidlet extends MIDlet implements CommandListener{

public Display display;
public Form discoveryForm;
public Form readyToConnectForm;
public Form dataViewForm;
public ImageItem mainImageItem;
public Image mainImage;
public Image bt_logo;
public TextField addressTextField;
public TextField subjectTextField;
public TextField messageTextField;
public Command selectCommand;
public Command exitCommand;
public Command connectCommand;
public List devicesList;
public Thread btUtility;
public String btConnectionURL;
//public StreamConnection connection;
//public InputStream in;
public boolean readData = false;

public BluetoothGPSMidlet() {
display=Display.getDisplay(this);
discoveryForm = new Form("Bluetooth GPS");

try{
mainImage = Image.createImage("/btlogoBIG.png");
bt_logo = Image.createImage("/btlogo.png");
} catch (java.io.IOException e){
e.printStackTrace();
}
mainImageItem = new ImageItem("Bluetooth GPS Reader", mainImage, Item.LAYOUT_CENTER, "");
discoveryForm.append(mainImageItem);
discoveryForm.append("\nThis application will scan the area for Bluetooth devices and determine if any are offering wireless serial port services.\n\n");

btUtility = new BTUtility();

/// discoveryForm initialization

exitCommand = new Command("Exit", Command.EXIT, 1);
discoveryForm.addCommand(exitCommand);
discoveryForm.setCommandListener(this);

/// devicesList initialization

devicesList = new List("Select a Bluetooth Device", Choice.IMPLICIT, new String[0], new Image[0]);
selectCommand = new Command("Select", Command.ITEM, 1);
devicesList.addCommand(selectCommand);
devicesList.setCommandListener(this);
devicesList.setSelectedFlags(new boolean[0]);

/// readyToConnectForm initialization

readyToConnectForm = new Form("Ready to Connect");
readyToConnectForm.append("The selected Bluetooth device is currently offering a valid serial port service, and is ready to connect. Please click on the 'Connect' button to connect and read the data.");
connectCommand = new Command("Connect", Command.ITEM, 1);
readyToConnectForm.addCommand(connectCommand);
readyToConnectForm.setCommandListener(this);

/// dataViewForm initialization

dataViewForm = new Form("Serial Data Viewer");
dataViewForm.append("The following lines of data are being read from the serial input:\n\n");
dataViewForm.addCommand(exitCommand);
dataViewForm.setCommandListener(this);

}


public void commandAction(Command command, Displayable d) {
if(command == selectCommand) {
btUtility.start();
}
if(command == exitCommand ) {
readData = false;
destroyApp(true);
}
if(command == connectCommand ) {
Thread commReaderThread = new COMMReader();
commReaderThread.start();
display.setCurrent(dataViewForm);
}
}


public void startApp() {
display.setCurrent(discoveryForm);
}


public void pauseApp() {

}

public void destroyApp(boolean b) {
notifyDestroyed();
}


////////////////

/**
* This is an inner class that is used for finding
* Bluetooth devices in the vicinity
*
*/
class BTUtility extends Thread implements DiscoveryListener {

Vector remoteDevices = new Vector();
Vector deviceNames = new Vector();

DiscoveryAgent discoveryAgent;

// obviously, 0x1101 is the UUID for
// the Serial Profile
UUID[] uuidSet = {new UUID(0x1101) };

// 0x0100 is the attribute for the service name element
// in the service record
int[] attrSet = {0x0100};


public BTUtility() {
try {
LocalDevice localDevice = LocalDevice.getLocalDevice();
discoveryAgent = localDevice.getDiscoveryAgent();
discoveryForm.append(" Searching for Bluetooth devices in the vicinity...\n");
discoveryAgent.startInquiry(DiscoveryAgent.GIAC, this);

} catch(Exception e) {
e.printStackTrace();
}
}

public void deviceDiscovered(RemoteDevice remoteDevice, DeviceClass cod) {
try{
discoveryForm.append("found: " + remoteDevice.getFriendlyName(true));
} catch(Exception e){
discoveryForm.append("found: " + remoteDevice.getBluetoothAddress());
} finally{
remoteDevices.addElement(remoteDevice);
}
}



public void inquiryCompleted(int discType) {

if (remoteDevices.size() > 0) {

// the discovery process was a success
// so let's out them in a List and display it to the user
for (int i=0; i try{
devicesList.append(((RemoteDevice)remoteDevices.elementAt(i)).getFriendlyName(true), bt_logo);
} catch (Exception e){
devicesList.append(((RemoteDevice)remoteDevices.elementAt(i)).getBluetoothAddress(), bt_logo);
}
}
display.setCurrent(devicesList);
} else {
// handle this
}

}


public void run(){

try {
RemoteDevice remoteDevice = (RemoteDevice)remoteDevices.elementAt(devicesList.getSelectedIndex());
discoveryAgent.searchServices(attrSet, uuidSet, remoteDevice , this);

} catch(Exception e) {
e.printStackTrace();
}
}



public void servicesDiscovered(int transID, ServiceRecord[] servRecord){

for(int i = 0; i < servRecord.length; i++) {

DataElement serviceNameElement = servRecord[i].getAttributeValue(0x0100);
String _serviceName = (String)serviceNameElement.getValue();
String serviceName = _serviceName.trim();
btConnectionURL = servRecord[i].getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);

}
display.setCurrent(readyToConnectForm);
readyToConnectForm.append("\n\nNote: the connection URL is: " + btConnectionURL);

}

public void serviceSearchCompleted(int transID, int respCode) {

if (respCode == DiscoveryListener.SERVICE_SEARCH_COMPLETED) {
// the service search process was successful

} else {
// the service search process has failed
}

}

}
////////////////


////////////////

/**
* This is an inner class that is used for reading
* the serial stream of data from a RFCOMM device
*
*/
class COMMReader extends Thread {

public COMMReader() {

}

public void run(){

try{
StreamConnection connection = (StreamConnection)Connector.open(btConnectionURL);

//
// open an input stream to get some data
//

InputStream in = connection.openInputStream();

byte[] serialData;
readData = true;
while(readData == true){
int lengthavai=0;
lengthavai = in.available();

if(lengthavai > 0){
serialData = new byte[lengthavai];
int length = in.read(serialData);
System.out.println("data read: " + new String(serialData));
dataViewForm.append(new String(serialData));
}
}

in.close();
connection.close();

}catch(IOException ioe){
ioe.printStackTrace();
}


}


}

}