Friday, November 23, 2018

Learn Swift on Ubuntu: install and compile

Swift is a new language developed by Apple. Recently, I am studying Swift so that I can build iOS or macOS apps. In this post, I will go over how to setup Swift environment on Ubuntu 18.04 LTS.

First, install clang
$ sudo apt-get update && sudo apt-get install clang -y

Next, download Swift from Swift.org
$ wget https://swift.org/builds/swift-4.2.1-release/ubuntu1804/swift-4.2.1-RELEASE/swift-4.2.1-RELEASE-ubuntu18.04.tar.gz

Decompress
$ tar xfz swift-4.2.1-RELEASE-ubuntu18.04.tar.gz

Add swift binary directory to your PATH environment
$ export PATH=/path/to/swift/usr/bin:${PATH}

This is it for setting up the environment. Let's now build "hello world" in Swift.

Create hello.swift with the following content:
print("hello world")

To run your code, simply run
$ swift hello.swift
hello world

To compile and create a binary, run
$ swiftc hello.swift
./hello
hello world

That's it for this post. Happy hacking!

Sunday, November 4, 2018

Simple 2-Way Chat with Java

In this post, I'm going to discuss how to create a simple chat application with Java. Basically, this is going to be a tutorial on Socket API and Java Thread API.

Here is the basic idea. A chat class should be running two tasks simultaneously: one is to send messages that the user inputs, and the other is to receive incoming message from the other side. Because these two tasks should be run simultaneously, we will need to implement a multi-threaded application.

I am going to let the main thread take care of user input and transmitting over to the other side, and a separate thread for receiving any incoming messages. Here we go.

So, the base class is ChatThread, which pretty much takes care of what I described above. The main thread takes care of user input and transmitting over to the other side, whereas a separate thread is going to run in the background, which receives incoming messages.

For this 2-way simple application, there are only two sides: one for server and the other for client. The server needs to take care of creating the server socket and wait for a client to join. Once the client joins, the server starts the ChatThread. The client will simply join the server and start the chatThread.

The implementation here is very basic and doesn't take care of properly exiting the connections. However, this should give you good introduction as to how to deal with socket programming and threading.

Happy hacking!