Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.*;
- import java.net.*;
- import java.util.Date;
- //======================================================================
- public class Server_1{
- // zmienne predefiniowane ==========================================
- int port = 12345;
- String host = "192.168.10.147";
- // zmienne niezainicjowane -----------------------------------------
- ServerSocket serverSocket;
- Socket connection = null;
- DataOutputStream out;
- DataInputStream in;
- String message;
- // konstruktor =====================================================
- Server_1(){}
- // metoda obslugujaca klientow =====================================
- void run(){
- try{
- // tworzymy nowe gniazdo -----------------------------------
- serverSocket = new ServerSocket( port, 5 );
- // akceptujemy polaczenie ----------------------------------
- connection = serverSocket.accept();
- // wyswietlamy informacje o polaczeniu ---------------------
- System.out.println("Address: " + connection.getInetAddress() + " Port: " + connection.getPort() );
- // pobieramy obiekty reprezentujace strumienie IN i OUT ----
- out = new DataOutputStream(connection.getOutputStream());
- out.flush();
- in = new DataInputStream(connection.getInputStream());
- getMessage();
- }
- catch(IOException ioException){
- ioException.printStackTrace();
- }
- finally{
- // zamykamy strumienie: wejsciowy i wyjsciowy --------------
- try{
- in.close();
- out.close();
- // zamykamy gniazdo ------------------------------------
- serverSocket.close();
- }
- catch(IOException ioException){
- ioException.printStackTrace();
- }
- }
- }
- // metoda odpowiadajaca za wysylanie wiadomosci do klientow ========
- void sendMessage(String msg) {
- try{
- byte[] data = msg.getBytes();
- out.writeInt( data.length );
- out.write ( data );
- out.flush();
- }
- catch(IOException ioException){
- ioException.printStackTrace();
- }
- }
- void getMessage(){
- try{
- if(in != null){
- byte[] buffer = new byte[256];
- int read;
- int totalRead = 0;
- // read = in.read(buffer);
- // System.out.println(((int)buffer[0])+"read:" + read);
- // read = in.read(buffer);
- // System.out.println((int)buffer[1]);
- while((read = in.read(buffer)) != -1){
- totalRead++;
- System.out.println(new String(buffer, "UTF8"));
- }
- System.out.println(totalRead);
- }
- }catch(Exception e){
- System.out.println("eksepszyn");
- }
- }
- // MAIN ============================================================
- public static void main(String args[]){
- Server_1 server = new Server_1();
- while(true){ // obslugujemy klientow w petli nieskonczonej -----
- server.run();
- }
- }
- //==================================================================
- }
- //======================================================================
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement