original source : https://www.geeksforgeeks.org/socket-programming-in-java/

Socket Programming in Java

This article describes a very basic one-way Client and Server setup where a Client connects, sends messages to server and the server shows them using socket connection. There’s a lot of low-level stuff that needs to happen for these things to work but the Java API networking package (java.net) takes care of all of that, making network programming very easy for programmers.

Client Side Programming

Establish a Socket Connection

To connect to other machine we need a socket connection. A socket connection means the two machines have information about each other’s network location (IP Address) and TCP port.The java.net.Socket class represents a Socket. To open a socket:

Socket socket = new Socket(“127.0.0.1”, 5000)
  • First argument – IP address of Server. ( 127.0.0.1  is the IP address of localhost, where code will run on single stand-alone machine).
  • Second argument – TCP Port. (Just a number representing which application to run on a server. For example, HTTP runs on port 80. Port number can be from 0 to 65535)

Communication

To communicate over a socket connection, streams are used to both input and output the data.

Closing the connection

The socket connection is closed explicitly once the message to server is sent.

In the program, Client keeps reading input from user and sends to the server until “Over” is typed.

Java Implementation

// A Java program for a Client
import java.net.*;
import java.io.*;

public class Client
{
// initialize socket and input output streams
private Socket socket = null;
private DataInputStream input = null;
private DataOutputStream out = null;

// constructor to put ip address and port
public Client(String address, int port)
{
// establish a connection
try
{
socket = new Socket(address, port);
System.out.println(“Connected”);

// takes input from terminal
input = new DataInputStream(System.in);

// sends output to the socket
out = new DataOutputStream(socket.getOutputStream());
}
catch(UnknownHostException u)
{
System.out.println(u);
}
catch(IOException i)
{
System.out.println(i);
}

// string to read message from input
String line = “”;

// keep reading until “Over” is input
while (!line.equals(“Over”))
{
try
{
line = input.readLine();
out.writeUTF(line);
}
catch(IOException i)
{
System.out.println(i);
}
}

// close the connection
try
{
input.close();
out.close();
socket.close();
}
catch(IOException i)
{
System.out.println(i);
}
}

public static void main(String args[])
{
Client client = new Client(“127.0.0.1”, 5000);
}
}

Server Programming

Establish a Socket Connection

To write a server application two sockets are needed.

  • A ServerSocket which waits for the client requests (when a client makes a new Socket())
  • A plain old Socket socket to use for communication with the client.

Communication

getOutputStream() method is used to send the output through the socket.

Close the Connection

After finishing,  it is important to close the connection by closing the socket as well as input/output streams.

// A Java program for a Server
import java.net.*;
import java.io.*;

public class Server
{
//initialize socket and input stream
private Socket socket = null;
private ServerSocket server = null;
private DataInputStream in = null;

// constructor with port
public Server(int port)
{
// starts server and waits for a connection
try
{
server = new ServerSocket(port);
System.out.println(“Server started”);

System.out.println(“Waiting for a client …”);

socket = server.accept();
System.out.println(“Client accepted”);

// takes input from the client socket
in = new DataInputStream(
new BufferedInputStream(socket.getInputStream()));

String line = “”;

// reads message from client until “Over” is sent
while (!line.equals(“Over”))
{
try
{
line = in.readUTF();
System.out.println(line);

}
catch(IOException i)
{
System.out.println(i);
}
}
System.out.println(“Closing connection”);

// close connection
socket.close();
in.close();
}
catch(IOException i)
{
System.out.println(i);
}
}

public static void main(String args[])
{
Server server = new Server(5000);
}
}

Important Points

  • Server application makes a ServerSocket on a specific port which is 5000. This starts our Server listening for client requests coming in for port 5000.
  • Then Server makes a new Socket to communicate with the client.
socket = server.accept()
  • The accept() method blocks(just sits there) until a client connects to the server.
  • Then we take input from the socket using getInputStream() method. Our Server keeps receiving messages until the Client sends “Over”.
  • After we’re done we close the connection by closing the socket and the input stream.
  • To run the Client and Server application on your machine, compile both of them. Then first run the server application and then run the Client application.

To run on Terminal or Command Prompt

Open two windows one for Server and another for Client

1. First run the Server application as ,

$ java Server

Server started
Waiting for a client …

2. Then run the Client application on another terminal as,

$ java Client

It will show – Connected and the server accepts the client and shows,

Client accepted

3. Then you can start typing messages in the Client window. Here is a sample input to the Client

Hello
I made my first socket connection
Over

Which the Server simultaneously receives and shows,

Hello
I made my first socket connection
Over
Closing connection

Notice that sending “Over” closes the connection between the Client and the Server just like said before.

If you’re using Eclipse or likes of such-

  1. Compile both of them on two different terminals or tabs
  2. Run the Server program first
  3. Then run the Client program
  4. Type messages in the Client Window which will be received and showed by the Server Window simultaneously.
  5. Type Over to end.

This article is contributed by Souradeep Barua. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

또 다른 socket programming in java 설명

original source : https://www.javatpoint.com/socket-programming

Java Socket Programming

Java Socket programming is used for communication between the applications running on different JRE.

Java Socket programming can be connection-oriented or connection-less.

Socket and ServerSocket classes are used for connection-oriented socket programming and DatagramSocket and DatagramPacket classes are used for connection-less socket programming.

The client in socket programming must know two information:

  1. IP Address of Server, and
  2. Port number.

Here, we are going to make one-way client and server communication. In this application, client sends a message to the server, server reads the message and prints it. Here, two classes are being used: Socket and ServerSocket. The Socket class is used to communicate client and server. Through this class, we can read and write message. The ServerSocket class is used at server-side. The accept() method of ServerSocket class blocks the console until the client is connected. After the successful connection of client, it returns the instance of Socket at server-side.

Socket class

A socket is simply an endpoint for communications between the machines. The Socket class can be used to create a socket.

Important methodsMethodDescription

1) public InputStream getInputStream()

          returns the InputStream attached with this socket.

2) public OutputStream getOutputStream()

          returns the OutputStream attached with this socket.

3) public synchronized void close()

          closes this socket

ServerSocket class

The ServerSocket class can be used to create a server socket. This object is used to establish communication with the clients.

Important methodsMethodDescription

1) public Socket accept()

          returns the socket and establish a connection between server and client.

2) public synchronized void close()

          closes the server socket.

Example of Java Socket Programming

Creating Server:

To create the server application, we need to create the instance of ServerSocket class. Here, we are using 6666 port number for the communication between the client and server. You may also choose any other port number. The accept() method waits for the client. If clients connects with the given port number, it returns an instance of Socket.

  1. ServerSocket ss=new ServerSocket(6666);  
  2. Socket s=ss.accept();//establishes connection and waits for the client  

Creating Client:

To create the client application, we need to create the instance of Socket class. Here, we need to pass the IP address or hostname of the Server and a port number. Here, we are using “localhost” because our server is running on same system.

  1. Socket s=new Socket(“localhost”,6666);  

Let’s see a simple of Java socket programming where client sends a text and server receives and prints it.

File: MyServer.java

  1. import java.io.*;  
  2. import java.net.*;  
  3. public class MyServer {  
  4. public static void main(String[] args){  
  5. try{  
  6. ServerSocket ss=new ServerSocket(6666);  
  7. Socket s=ss.accept();//establishes connection  
  8. DataInputStream dis=new DataInputStream(s.getInputStream());  
  9. String  str=(String)dis.readUTF();  
  10. System.out.println(“message= ”+str);  
  11. ss.close();  
  12. }catch(Exception e){System.out.println(e);}  
  13. }  
  14. }  

File: MyClient.java

  1. import java.io.*;  
  2. import java.net.*;  
  3. public class MyClient {  
  4. public static void main(String[] args) {  
  5. try{      
  6. Socket s=new Socket(“localhost”,6666);  
  7. DataOutputStream dout=new DataOutputStream(s.getOutputStream());  
  8. dout.writeUTF(“Hello Server”);  
  9. dout.flush();  
  10. dout.close();  
  11. s.close();  
  12. }catch(Exception e){System.out.println(e);}  
  13. }  
  14. }  

download this example

To execute this program open two command prompts and execute each program at each command prompt as displayed in the below figure.

After running the client application, a message will be displayed on the server console.

Example of Java Socket Programming (Read-Write both side)

In this example, client will write first to the server then server will receive and print the text. Then server will write to the client and client will receive and print the text. The step goes on.

File: MyServer.java

  1. import java.net.*;  
  2. import java.io.*;  
  3. class MyServer{  
  4. public static void main(String args[])throws Exception{  
  5. ServerSocket ss=new ServerSocket(3333);  
  6. Socket s=ss.accept();  
  7. DataInputStream din=new DataInputStream(s.getInputStream());  
  8. DataOutputStream dout=new DataOutputStream(s.getOutputStream());  
  9. BufferedReader br=new BufferedReader(new InputStreamReader(System.in));  
  10.  
  11. String str=“”,str2=“”;  
  12. while(!str.equals(“stop”)){  
  13. str=din.readUTF();  
  14. System.out.println(“client says: ”+str);  
  15. str2=br.readLine();  
  16. dout.writeUTF(str2);  
  17. dout.flush();  
  18. }  
  19. din.close();  
  20. s.close();  
  21. ss.close();  
  22. }}  

File: MyClient.java

  1. import java.net.*;  
  2. import java.io.*;  
  3. class MyClient{  
  4. public static void main(String args[])throws Exception{  
  5. Socket s=new Socket(“localhost”,3333);  
  6. DataInputStream din=new DataInputStream(s.getInputStream());  
  7. DataOutputStream dout=new DataOutputStream(s.getOutputStream());  
  8. BufferedReader br=new BufferedReader(new InputStreamReader(System.in));  
  9.  
  10. String str=“”,str2=“”;  
  11. while(!str.equals(“stop”)){  
  12. str=br.readLine();  
  13. dout.writeUTF(str);  
  14. dout.flush();  
  15. str2=din.readUTF();  
  16. System.out.println(“Server says: ”+str2);  
  17. }  
  18.  
  19. dout.close();  
  20. s.close();  
  21. }}  

css display , visibility property vs android visibility

p.ex1 {display: none;}
p.ex2 {display: inline;}
p.ex3 {display: block;}
p.ex4 {display: inline-block;}

h2.a {
 visibility: visible;
}

h2.b {
 visibility: hidden;
}

Visible

XML file: android:visibility=“visible”

Java code: view.setVisibility(View.VISIBLE);

invisible

XML file: android:visibility=“invisible”

Java code: view.setVisibility(View.INVISIBLE);

Hiding (GONE)

XML file: android: visibility = “go”

Java code: view.setVisibility(View.GONE);

https://youtu.be/bc6wW-g6uss tacademy의 android content provider를 공부하다 찾아보게 된 자료이다. 

original source : https://stackoverflow.com/a/31600191

http://developer.android.com/guide/topics/providers/content-providers.html

Content providers manage access to a structured set of data. They encapsulate the data, and provide mechanisms for defining data security. Content providers are the standard interface that connects data in one process with code running in another process.

구조를 가진 data를 android에서 encapsulate해서도 다루는 경우가 있는데 이에 접근하는 경우 Uri 를 이용한다. content provider를 이용하는 경우 process간 data를 공유할수 있게 된다. 즉 다른 app간에 data를 공유할수 있게 된다는 이야기이다. 

https://developer.android.com/guide/topics/providers/content-providers.html?authuser=1

content provider 에 대한 google doc (길지 않고 개념 잡기 좋다)

Content providers

Content providers can help an application manage access to data stored by itself, stored by other apps, and provide a way to share data with other apps. They encapsulate the data, and provide mechanisms for defining data security. Content providers are the standard interface that connects data in one process with code running in another process. Implementing a content provider has many advantages. Most importantly you can configure a content provider to allow other applications to securely access and modify your app data as illustrated in figure 1.

image

Figure 1. Overview diagram of how content providers manage access to storage.

Use content providers if you plan to share data. If you don’t plan to share data, you may still use them because they provide a nice abstraction, but you don’t have to. This abstraction allows you to make modifications to your application data storage implementation without affecting other existing applications that rely on access to your data. In this scenario only your content provider is affected and not the applications that access it. For example, you might swap out a SQLite database for alternative storage as illustrated in figure 2.

Figure 2. Illustration of migrating content provider storage.

image

A number of other classes rely on the ContentProvider class:

If you are making use of any of these classes you also need to implement a content provider in your application. Note that when working with the sync adapter framework you can also create a stub content provider as an alternative. For more information about this topic, see Creating a stub content provider. In addition, you need your own content provider in the following cases:

  • You want to implement custom search suggestions in your application
  • You need to use a content provider to expose your application data to widgets
  • You want to copy and paste complex data or files from your application to other applications

The Android framework includes content providers that manage data such as audio, video, images, and personal contact information. You can see some of them listed in the reference documentation for the android.provider package. With some restrictions, these providers are accessible to any Android application.

A content provider can be used to manage access to a variety of data storage sources, including both structured data, such as a SQLite relational database, or unstructured data such as image files. For more information on the types of storage available on Android, see Storage options, as well as Designing data storage.

Advantages of content providers

Content providers offer granular control over the permissions for accessing data. You can choose to restrict access to a content provider from solely within your application, grant blanket permission to access data from other applications, or configure different permissions for reading and writing data. For more information on using content providers securely, see Security tips for storing data, as well as Content provider permissions.

You can use a content provider to abstract away the details for accessing different data sources in your application. For example, your application might store structured records in a SQLite database, as well as video and audio files. You can use a content provider to access all of this data, if you implement this development pattern in your application.

Also note that CursorLoader objects rely on content providers to run asynchronous queries and then return the results to the UI layer in your application. For more information on using a CursorLoader to load data in the background, see Running a query with a CursorLoader.

The following topics describe content providers in more detail:

Content provider basics

How to access and update data using an existing content provider.

Creating a content provider

How to design and implement your own content provider.

Calendar provider

How to access the Calendar provider that is part of the Android platform.

Contacts provider

How to access the Contacts provider that is part of the Android platform.

For sample code related to this page, refer to the Basic Sync Adapter sample application

original source : https://www.tutorialspoint.com/android/android_content_providers.htm

위 링크를 가면 실제 custom content provider를 만드는 과정과 실제 예제 코드가 있다.

A content provider component supplies data from one application to others on request. Such requests are handled by the methods of the ContentResolver class. A content provider can use different ways to store its data and the data can be stored in a database, in files, or even over a network.

ContentProvider

sometimes it is required to share data across applications. This is where content providers become very useful.

Content providers let you centralize content in one place and have many different applications access it as needed. A content provider behaves very much like a database where you can query it, edit its content, as well as add or delete content using insert(), update(), delete(), and query() methods. In most cases this data is stored in an SQlite database.

A content provider is implemented as a subclass of ContentProvider class and must implement a standard set of APIs that enable other applications to perform transactions.

public class My Application extends  ContentProvider {
}

Content URIs

To query a content provider, you specify the query string in the form of a URI which has following format −

<prefix>://<authority>/<data_type>/<id>

Here is the detail of various parts of the URI −

Create Content Provider

This involves number of simple steps to create your own content provider.

  • First of all you need to create a Content Provider class that extends the ContentProviderbaseclass.
  • Second, you need to define your content provider URI address which will be used to access the content.
  • Next you will need to create your own database to keep the content. Usually, Android uses SQLite database and framework needs to override onCreate() method which will use SQLite Open Helper method to create or open the provider’s database. When your application is launched, the onCreate() handler of each of its Content Providers is called on the main application thread.
  • Next you will have to implement Content Provider queries to perform different database specific operations.
  • Finally register your Content Provider in your activity file using <provider> tag.

Here is the list of methods which you need to override in Content Provider class to have your Content Provider working −

ContentProvider

  • onCreate() This method is called when the provider is started.
  • query() This method receives a request from a client. The result is returned as a Cursor object.
  • insert()This method inserts a new record into the content provider.
  • delete() This method deletes an existing record from the content provider.
  • update() This method updates an existing record from the content provider.
  • getType() This method returns the MIME type of the data at the given URI.

https://youtu.be/zBO_0_7huVA tacademy 동영상를 보다가 이해가 부족하여 다른 자료를 찾게 되었다. 

original source : https://www.tutorialspoint.com/android/android_clipboard.htm

Android provides the clipboard framework for copying and pasting different types of data. The data could be text, images, binary stream data or other complex data types.

Android provides the library of ClipboardManager and ClipData and ClipData.item to use the copying and pasting framework.In order to use clipboard framework, you need to put data into clip object, and then put that object into system wide clipboard.

In order to use clipboard , you need to instantiate an object of ClipboardManager by calling the getSystemService() method. Its syntax is given below −

ClipboardManager myClipboard;
myClipboard = (ClipboardManager)getSystemService(CLIPBOARD_SERVICE);

Copying data

The next thing you need to do is to instantiate the ClipData object by calling the respective type of data method of the ClipData class. In case of text data , the newPlainText method will be called. After that you have to set that data as the clip of the Clipboard Manager object.Its syntax is given below −

ClipData myClip;
String text = "hello world";
myClip = ClipData.newPlainText("text", text);
myClipboard.setPrimaryClip(myClip);

The ClipData object can take these three form and following functions are used to create those forms.

Pasting data

In order to paste the data, we will first get the clip by calling the getPrimaryClip() method. And from that click we will get the item in ClipData.Item object. And from the object we will get the data. Its syntax is given below −

ClipData abc = myClipboard.getPrimaryClip();
ClipData.Item item = abc.getItemAt(0);
String text = item.getText().toString();

Apart from the these methods , there are other methods provided by the ClipboardManager class for managing clipboard framework. These methods are listed below −

original source : https://www.includehelp.com/android/use-clipboardmanager-to-clipdata.aspx

초간단 ClipboardManager와 ClipData 구현 예시

original source : https://stackoverflow.com/a/4577249

Here are some definitions:

  • A Surface is an object holding pixels that are being composited to the screen. Every window you see on the screen (a dialog, your full-screen activity, the status bar) has its own surface that it draws in to, and Surface Flinger renders these to the final display in their correct Z-order. A surface typically has more than one buffer (usually two) to do double-buffered rendering: the application can be drawing its next UI state while the surface flinger is compositing the screen using the last buffer, without needing to wait for the application to finish drawing.
  • A window is basically like you think of a window on the desktop. It has a single Surface in which the contents of the window is rendered. An application interacts with the Window Manager to create windows; the Window Manager creates a Surface for each window and gives it to the application for drawing. The application can draw whatever it wants in the Surface; to the Window Manager it is just an opaque rectangle.
  • A View is an interactive UI element inside of a window. A window has a single view hierarchy attached to it, which provides all of the behavior of the window. Whenever the window needs to be redrawn (such as because a view has invalidated itself), this is done into the window’s Surface. The Surface is locked, which returns a Canvas that can be used to draw into it. A draw traversal is done down the hierarchy, handing the Canvas down for each view to draw its part of the UI. Once done, the Surface is unlocked and posted so that the just drawn buffer is swapped to the foreground to then be composited to the screen by Surface Flinger.
  • A SurfaceView is a special implementation of View that also creates its own dedicated Surface for the application to directly draw into (outside of the normal view hierarchy, which otherwise must share the single Surface for the window). The way this works is simpler than you may expect – all SurfaceView does is ask the window manager to create a new window, telling it to Z-order that window either immediately behind or in front of the SurfaceView’s window, and positioning it to match where the SurfaceView appears in the containing window. If the surface is being placed behind the main window (in Z order), SurfaceView also fills its part of the main window with transparency so that the surface can be seen.
  • A Bitmap is just an interface to some pixel data. The pixels may be allocated by Bitmap itself when you are directly creating one, or it may be pointing to pixels it doesn’t own such as what internally happens to hook a Canvas up to a Surface for drawing. (A Bitmap is created and pointed to the current drawing buffer of the Surface.)

Also please keep in mind that, as this implies, a SurfaceView is a pretty heavy-weight object. If you have multiple SurfaceViews in a particular UI, stop and think about whether this is really needed. If you have more than two, you almost certainly have too many.

original source : https://stackoverflow.com/a/38496500

image

original source : https://stackoverflow.com/a/38496500

In one sentence, A Window is a rectangular area which has one view hierarchy. Colored rectangles in below image are windows.

image

As you can see, there can be multiple windows in one screen, and WindowManager manages them. 

According to Android Developer Documentation,

“Each activity is given a window in which to draw its user interface.”

and, Dianne Hackborn, who is a Android framework engineer, gave some definitions here. (1시간 분량) She said,

A window is basically like you think of a window on the desktop. It has a single Surface in which the contents of the window is rendered. An application interacts with the Window Manager to create windows; the Window Manager creates a Surface for each window and gives it to the application for drawing. The application can draw whatever it wants in the Surface; to the Window Manager it is just an opaque rectangle.

A Surface is an object holding pixels that are being composited to the screen. Every window you see on the screen (a dialog, your full-screen activity, the status bar) has its own surface that it draws in to, and Surface Flinger renders these to the final display in their correct Z-order. A surface typically has more than one buffer (usually two) to do double-buffered rendering: the application can be drawing its next UI state while the surface flinger is compositing the screen using the last buffer, without needing to wait for the application to finish drawing.

A View is an interactive UI element inside of a window. A window has a single view hierarchy attached to it, which provides all of the behavior of the window. Whenever the window needs to be redrawn (such as because a view has invalidated itself), this is done into the window’s Surface. The Surface is locked, which returns a Canvas that can be used to draw into it. A draw traversal is done down the hierarchy, handing the Canvas down for each view to draw its part of the UI. Once done, the Surface is unlocked and posted so that the just drawn buffer is swapped to the foreground to then be composited to the screen by Surface Flinger.

Also, I found some other info from Romain Guy’s presentation(You can watch his talk at San Francisco Android user group from here, and download full slides from here)

So, in a nutshell:

  • An Activity has a window (in which it draws its user interface),
  • a Window has a single Surface and a single view hierarchy attached to it,
  • a Surface include ViewGroup which holds views.

original source : https://youtu.be/vfnoT4TRmws

The Android Canvas, bitmap, paint에 관한 설명 1:00 부터 보면된다.