java & swift socket communication(tcp 소켓통신)

자바와 스위프트 간에 소켓통신하기

이승연
이승연
Jul 26, 2017 · 6 min read

server = Java

client = swift

1. swift 3 socket communication code

아래의 사이트에서 참고했습니다.

1. cocoapod 설치

이미 cocoapod를 설치했다면 이 단계를 생략합니다.

gem install cocoapods

2. Podfile 생성

터미널에서 프로젝트 폴더로 간 후 아래 코드를 입력합니다.

pod init

3. Podfile 수정

Podfile을 엽니다.

open Podfile
pod ‘SwiftSocket’

4. pod install

터미널에 아래 코드를 입력합니다.

pod install

5. xcode에 코드 입력.

import UIKitimport SwiftSocketclass ViewController: UIViewController {@IBOutlet weak var textView: UITextView!let host = "127.0.0.1"let port = 9999var client: TCPClient?override func viewDidLoad() {super.viewDidLoad()client = TCPClient(address: host, port: Int32(port))}@IBAction func sendButtonAction(_ sender: Any) {guard let client = client else { return }switch client.connect(timeout: 10) {case .success:appendToTextField(string: "Connected to host \(client.address)")if let response = sendRequest(string: "GET / HTTP/1.0\n\n", using: client) {appendToTextField(string: "Response: \(response)")}case .failure(let error):appendToTextField(string: String(describing: error))}}private func sendRequest(string: String, using client: TCPClient) -> String? {appendToTextField(string: "Sending data ... ")switch client.send(string: string) {case .success:return readResponse(from: client)case .failure(let error):appendToTextField(string: String(describing: error))return nil}}private func readResponse(from client: TCPClient) -> String? {guard let response = client.read(1024*10) else { return nil }return String(bytes: response, encoding: .utf8)}private func appendToTextField(string: String) {print(string)textView.text = textView.text.appending("\n\(string)")}}

5–1 같은 기기에서의 소켓통신

위의 코드처럼 이 주소를 사용합니다. 코드를 변경할 필요 없이 그대로 사용하시면 됩니다.

let host = "127.0.0.1"

5–2 다른 기기 간의 소켓통신

먼저 다른 기기와 소켓통신을 하기 위해서는 같은 네트워크에 연결되어있어야합니다.

ifconfig
let host = "192.168.0.4"

2. JAVA socket communication code

아래의 블로그를 참고하시면 됩니다.

3. 결과

먼저 Server(Java)를 Run 한 뒤 Client(Swift)를 빌드합니다.

이승연

Written by

이승연

👩‍💻 세상의 모든 에러를 경험하는 중. https://github.com/sweepty

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade