W2
Week 2. Cross-Device Interaction (WebSocket)
1. Mobile Modality & Parametric Interface
Mobile Modality: The Phone as an Instrument
- Think of the classic "2001: A Space Odyssey" scene: a bone becomes a satellite. This represents the evolution of a tool.
- Steve Jobs introducing the iPhone in 2007 was a similar moment. It put a powerful new tool in our hands.
- The best tool we have is our fingers. The iPhone/smartphone is an instrument played by our fingers.
- Our Goal: To build interfaces that respond to this "performance."
- Instrumental Interface
Two Types of Interaction
-
1. Semantic Interaction (Meaning-based)
- What it is: Discontinuous, categorical. You make a clear choice.
- Examples: Clicking a button, selecting an option from a menu.
- Used in: Most practical interfaces (apps, websites).
-
2. Phenomenological Interaction (Experience-based)
- What it is: Continuous, flowing.
- Examples: Moving your body, dragging your finger, scrolling.
- Used in: Interactive art, games. Parametric Web Interface
-
What is it? An interface where your mobile interactions (inputs) are used to change parameters (variables).
-
Think of it like playing an instrument: your actions change the sound. Here, your actions change the context, the time, or the space.
-
Example: Changing Time
- Semantic way: Typing "8:00 AM" in a box.
- Phenomenological way: Dragging a dial, like the iOS Alarm clock. (iOS Wheel Picker - inspired from Las Vegas)
- Question: Which is more intuitive? More fun?
-
Example: Changing Season
- Semantic way: 4 separate buttons ("Spring," "Summer," "Fall," "Winter").
- Phenomenological way: A continuous X-axis or Y-axis slider that blends between seasons.
-
Example: Changing Job
- Semantic way: A dropdown list of pre-set jobs.
- Phenomenological way: A "blurry" selection space where you can slide between different job categories.
Input Materials (The "Keys" of Your Instrument)
- I. Selection / Navigation (Broad Control)
- Scrolling
- Swiping (e.g., Tinder-style card swipe)
- Zoom-in / Zoom-out
- II. Fine-Tuning (Precise Control)
- Finger-Skating / Sketching (drawing on the screen)
- Set of Togglers (on/off switches)
- Set of Sliders
- Set of Buttons
- Accelerometer (tilting the phone)
- Voice/Speech
- Semantic: Speech-to-Text (what you say)
- Non-Semantic: Volume size (how loud you are)
- Camera Tracking (Eye tracking, Object detection)
- Rotating & Zooming an object
2. Multi-Device Interaction
- Multi-Device Interaction: Using two or more devices
- Ex. Mobile: Input, Screen/Laptop: Output
- Ex. Banpo-Xism: multiple mobiles (input) → 1 media wall + 3 vertical TVs (output)
Single Device vs. Multi-Device
- Single Device (e.g., Laptop only)
- Structure: User Input (Mouse/Keyboard) → Parameter Conversion → Visual Output
- Inputs: Mouse click duration, mouse move velocity/path, keyboard typing speed.
- Artistic Strategy: "Verfremdungseffekt" (Defamiliarization effect) – making a normal interaction (like typing) create an unexpected result.
- Multi-Device Web Artwork (Our Focus)
- Input Device: Mobile (iOS / Android)
- Output Device: Laptop (1920 x 1080 screen)
- Why? Phone interactions (touch, tilt) have a different phenomenological feel than laptop interactions (mouse, keyboard).
Creating Your 'Visual Instrument'
- This is the core design structure for your project.
- The Flow: Mobile Input → Parameter Conversion + System Rules → Laptop Output
- Which Inputs to Use? (Mobile)
- Button 'Tab'
- Finger 'Swipe'
- Zoom, Pinch, Rotate
- Voice Input, Camera Input
- TTS/STT (Text-to-Speech, Speech-to-Text)
- LLM (sending prompts to an AI)
- Decibel (sound level)
- External Data (weather, traffic, stock prices)
- Which Outputs to Use? (Laptop)
- Creative Coding (, )
- Text / Typography (changing font, size, layout)
- Collage of Images / Videos
- 3D Graphics (e.g., using )
- Audio Elements (e.g., using )
3. Socket.io
- : Bi-directional real-time communication btw client/server, enabling real-time inter-device interaction in web applications
- : Javascript library, high-level abstraction of WebSocket, beginner-friendly (Automatic reconnection, Default fallback option)
- Strategy
- Let's say we have Client A (Interaction Input) and Client B (Interaction Output)
- Client A sends a message → the relay server forwards it to all other clients in the same room → Client B receives it
- Already installed in the template:
socket.io(server),socket.io-client(browser)
How it is structured in this repo
-
socket-server.mjs: the relay server. One file, port 4000join(room): A device joins a roommessage({ type, data }): Forwarded as-is to every other device in the same room- It is not part of Next.js. It is a separate Node process (that's why Vercel can't host it, see §7)
-
hooks/shared/useSocket.ts: the client-side hookconst { send, connected } = useSocket(room, onMessage)send(type, data): sends a message to the roomonMessage(type, data): called for every message from the other devices- Address:
NEXT_PUBLIC_SOCKET_URLif set, otherwise the current host at port 4000
-
Route convention for one experiment
- Both call
useSocket("<name>", ...)with the same room name
File Address Client A · Mobile app/experiments/w2/<name>/mobile/page.tsxlocalhost:3000/experiments/w2/name/mobile Client B · Screen app/experiments/w2/<name>/screen/page.tsxlocalhost:3000/experiments/w2/name/screen - Both call
Overall workflow
The five numbers of the diagram:
- Screen page opens:
useSocket("drawing", onMessage)connects to the relay and joins the room - Mobile page opens: the same
- Mobile:
send("move", { x, y }) - Relay: forwards
{ type: "move", data: { x, y } }to the rest of the room - Screen:
onMessage("move", { x, y })is called. Update your state, draw
- This is the base code. You can make it more complicated/add modularity on top of it
- What will be your speculative inter-device interaction? How will you use this technology to design your interactive/immersive audio-visual design practice?
- You can also connect Socket.io/WebSocket with TouchDesigner or Unreal (W3)
4. Socket.io Examples
In this repo (/experiments/w2)
- Drawing: touch move on mobile → line on screen (mobile · screen)
- Signature
- Typing: type on mobile → the sentence is sent in eight chat apps, every room answers (mobile · screen)
- 3D (Three.js)
- Rotate: drag on mobile → 3D shape turns on screen (mobile · screen)
- Particles: two fingers on mobile, pulled apart → a sphere breaks into 40,000 particles (mobile · screen)
- Togglers: finger-skating over 40 switches on mobile → 40 wave sources in a simulated surface (mobile · screen)
- City: three modes on mobile (Settings, Navigate, Statistics) → the parameters, the camera and the statistics of a generated city, with live sound (mobile · screen)
XD Lab works
5. Mobile HTTPS Debugging
- Mobile Debugging: Hard
- Cross-Device (Mobile + Desktop) Debugging: VERY HARD
A1. Local Network Connection
Open your laptop's page on your mobile. Keep pnpm dev running.
localhostmeans "this device itself". On your laptop, localhost:3000 is your laptop. Typed on your mobile, localhost is the mobile, and nothing runs there- So the mobile needs your laptop's address on the Wi-Fi: its IP address. The Wi-Fi router gives one to every device. It looks like 192.168.0.12 or 10.0.0.12
- Find your laptop's IP address. Two ways:
- In the Terminal
- macOS or Linux:
ifconfig | grep "inet " - Windows:
ipconfig - Take the address that looks like 192.168.x.x or 10.x.x.x. Not 127.0.0.1: that one is localhost
- macOS or Linux:
- Ask your AI agent: "What is my computer's local IP address?" It runs the command and tells you
- In the Terminal
- Connect the mobile and the laptop to the same Wi-Fi. If the school Wi-Fi blocks device-to-device traffic, use your mobile's hotspot
- On the mobile's browser, type
http://<YOUR_IP>:3000and the path. For example: http://192.168.0.12:3000/experiments/w2/drawing/mobile - On the laptop, open the screen page as before: localhost:3000/experiments/w2/drawing/screen
A2. for Local Dev: pnpm dev:mobile
Why HTTPS
http://: what the page and the browser send each other is not encrypted. Anyone on the same network can read ithttps://: it is encrypted. Only the page and the browser can read it- Camera, microphone and motion sensors show you and the room you are in. So browsers give them only to pages opened with
https:// - One exception:
localhost. Nothing leaves your own device there. That is why the camera worked on your laptop in W1 withpnpm dev - Your mobile opens the page with
http://192.168.x.x. That is not localhost, and not https. So the camera and the sensors are blocked, until you serve your page over https
How
- Stop the server that is running: press
Ctrl + Cin the terminal wherepnpm devruns - Start it again with
pnpm dev:mobile. The same two servers (3000 and 4000), now over https. The first time it may ask for your password. It prints the address for your mobile - On the mobile, open
https://<YOUR_IP>:3000and the path. A warning page appears ("Your connection is not private")- This is normal. The certificate that proves "this is really that site" was made by your own laptop, so the mobile cannot check it
- Tap "Advanced" → "Proceed (unsafe)"
- Do the same for the relay: open
https://<YOUR_IP>:4000on the mobile and pass the warning. You should see "socket relay ok"- If you skip this: the page loads but nothing arrives on the screen
- On the laptop, open https://localhost:3000
You only need to pass the warnings once per device.
A3. Remote Debugging (iOS vs. Android)
See your mobile's console.log() messages, DOM and network requests on your computer's screen.
Android (Chrome Debugging)
- On Your Android Device: Enable "Developer Options" (this is usually hidden; search how to enable it for your specific phone). Inside Developer Options, toggle on "USB Debugging".
- On Your Computer: Connect your phone to your computer with a USB cable.
- Open desktop Chrome and type
chrome://inspect#devicesinto the address bar. - You should see your device and any open tabs. Click "Inspect" on the tab you want to debug.
- A full DevTools window will open, allowing you to inspect your mobile browser session.
iOS (Safari Web Inspector)
Note: This process requires a Mac.
- On Your iPhone: Go to Settings > Safari > Advanced and toggle on "Web Inspector".
- On Your Mac: Open Safari. Go to Safari > Preferences > Advanced and tick the box at the bottom: "Show Develop menu in menu bar".
- Connect: Connect your iPhone to your Mac with a USB cable.
- On your Mac's Safari, click the new "Develop" menu. You should see your iPhone's name.
- Hover over your iPhone's name to see a list of open tabs. Click the tab you wish to debug to open a Web Inspector window.
6. Mobile Sensors
- Camera, microphone and motion sensors work only on (or localhost):
pnpm dev:mobile(A2) - They start after a user tap. The browser asks for permission
| Input | Browser API | Example | |
|---|---|---|---|
| Tilt | deviceorientation event → alpha, beta, gamma (degrees) | w2/tilt | |
| Shake | devicemotion event → acceleration | ||
| Microphone | navigator.mediaDevices.getUserMedia({ audio: true }) | w1/video | |
| Camera | navigator.mediaDevices.getUserMedia({ video: true }) | w2/camera-slit-scan · w1/glsl/creation-webcam |
Tilt (accelerometer)
- iOS:
DeviceOrientationEvent.requestPermission()inside a tap handler. Android: no permission pop-up
async function start() {
// iOS only: ask for permission (must be called from a tap)
const eventClass = DeviceOrientationEvent as unknown as { requestPermission?: () => Promise<string> };
if (eventClass.requestPermission) await eventClass.requestPermission();
window.addEventListener("deviceorientation", (event) => {
const x = (event.gamma ?? 0) / 45; // left / right
const y = (event.beta ?? 0) / 45; // front / back
send("tilt", { x, y });
});
}
- Full code:
app/experiments/w2/tilt/
Examples (HTTPS)
- Tilt: mobile tilt → ball on screen (mobile · screen)
- Camera Slit-Scan: mobile camera → slit-scan on screen (mobile · screen)
7. Socket Deployment
- Deployment (W1 §12): your app moves from localhost to a public address, on
- A multi-device piece is two programs (§3): the Next.js app (port 3000) and the relay,
socket-server.mjs(port 4000) - Vercel runs the Next.js app. It cannot run the relay
- Vercel is serverless: it runs your code only for the moment a page is requested, then stops
- The relay has to stay on all the time, holding the connection to the mobile and to the screen
- So the relay needs a computer that stays on. Two choices
1. Your laptop
- What we did in class:
pnpm dev(orpnpm dev:mobile) runs both programs on your laptop, and the mobile joins over the same Wi-Fi (§5) - No deployment. It works only on that Wi-Fi
2. A server on the internet
- The app goes on Vercel, as in W1. The relay goes on a hosting service that keeps a program running: or
- is another example. Banpo-Xism runs its relay there
- Then anyone can open your piece, from any network
- For the final in the Black Room, deploy this way
Telling the app where the relay is
- On your laptop, the app and the relay were on the same computer. The page did not need an address: it connected to "port 4000 of this computer"
- After deployment they are in two different places. The app is on Vercel, the relay is on Render, and each has its own address. The app does not know where the relay is, so you have to tell it
- You tell it with an environment variable on Vercel. An environment variable is a value you do not write in the code: you type it into the service's settings as "name = value", and the app reads it from there
- Name:
NEXT_PUBLIC_SOCKET_URL. The template'suseSocketlooks for the relay's address under this name - Value: the relay's address that Render gives you, for example
https://my-relay.onrender.com
- Name:
Step by step: Render
- The app: push your repo to GitHub and deploy it on Vercel (W1 §12)
- The relay: https://render.com → sign up → + New > Web Service → select the same GitHub repo → Connect
- Fill in the form. The Start Command is what makes this service run the relay, not the app
- Language:
Node - Build Command:
pnpm install - Start Command:
node socket-server.mjs - Compute:
Free - Environment Variables:
NODE_VERSION=24
- Language:
- Deploy. Render gives the relay an address,
https://<name>.onrender.com. Open it: it shows "socket relay ok" - Register this address on Vercel as an environment variable
- On Vercel, open your project → Settings → Environment Variables
- Type
NEXT_PUBLIC_SOCKET_URLinto Key andhttps://<name>.onrender.cominto Value, then press Save - Deploy again: Deployments → the ⋯ of the latest deployment → Redeploy. The value goes into the app when it is deployed, so it only takes effect after a new deployment
- Open
/screenon the laptop and/mobileon the mobile, both on the Vercel address
- Free plan: the relay sleeps after 15 minutes without use. The next connection takes about one minute
- Docs: Your first deploy · WebSockets · Free plan
Step by step: Railway
- The app: on Vercel, as above
- The relay: https://railway.com → sign up with GitHub → New Project → GitHub repo → select the same repo
- Service → Settings → Custom Start Command:
node socket-server.mjs→ Deploy - Service → Settings → Networking → Generate Domain. Open
https://<name>.up.railway.app: it shows "socket relay ok" - Register this address on Vercel as an environment variable: same as step 5 above, with the Railway address
- Trial: $5 credit, 30 days. After that $5/month
- Docs: Quick start · Build and start commands · Domains
8. Homework: Web Assignment 2
Build a Mobile-to-Laptop Interactive Experience. Due to Web 3 (11/16).
W2
2주차. 크로스 디바이스 인터랙션 (WebSocket)
1. 모바일 모달리티 & 파라메트릭 인터페이스
모바일 모달리티: 모바일이라는 악기
- 영화 "2001: 스페이스 오디세이"의 유명한 장면에서는 뼈가 인공위성으로 바뀐다. 도구의 진화를 보여주는 장면이다.
- 2007년 스티브 잡스가 아이폰을 발표한 순간도 비슷했다. 강력한 새 도구가 우리 손에 들어왔다.
- 우리가 가진 가장 좋은 도구는 손가락이다. 아이폰/스마트폰은 손가락으로 연주하는 악기다.
- 목표: 이 "연주"에 반응하는 인터페이스 만들기.
- 악기 같은 인터페이스 (Instrumental Interface)
인터랙션의 두 종류
-
1. 의미적 인터랙션 (Semantic, 의미 기반)
- 특징: 불연속적이고 범주가 나뉘어 있다. 하나를 분명하게 고른다.
- 예: 버튼 클릭, 메뉴에서 옵션 선택.
- 쓰이는 곳: 실용적인 인터페이스 대부분 (앱, 웹사이트).
-
2. 현상학적 인터랙션 (Phenomenological, 경험 기반)
- 특징: 연속적이고 끊김 없이 이어진다.
- 예: 몸 움직이기, 손가락으로 드래그하기, 스크롤.
- 쓰이는 곳: 인터랙티브 아트, 게임. 파라메트릭 웹 인터페이스
-
무엇인가? 모바일에서의 인터랙션(입력)으로 파라미터(변수)를 바꾸는 인터페이스.
-
악기 연주를 떠올리면 된다. 악기에서는 동작이 소리를 바꾼다. 여기서는 동작이 맥락, 시간, 공간을 바꾼다.
-
예: 시간 바꾸기
- 의미적 방식: 입력칸에 "8:00 AM"을 적는다.
- 현상학적 방식: iOS 알람처럼 다이얼을 돌린다. (iOS 휠 피커 - 라스베이거스에서 영감을 얻었다)
- 질문: 어느 쪽이 더 직관적인가? 어느 쪽이 더 재미있는가?
-
예: 계절 바꾸기
- 의미적 방식: 따로 떨어진 버튼 4개 ("봄", "여름", "가을", "겨울").
- 현상학적 방식: X축이나 Y축 슬라이더 하나. 움직이면 계절이 끊김 없이 섞이며 넘어간다.
-
예: 직업 바꾸기
- 의미적 방식: 미리 정해둔 직업이 나열된 드롭다운.
- 현상학적 방식: 경계가 "흐릿한" 선택 공간. 여러 직업군 사이를 미끄러지듯 오간다.
입력 재료 (악기의 "건반")
- I. 선택 / 내비게이션 (대략적인 조작)
- 스크롤
- 스와이프 (예: 틴더처럼 카드 넘기기)
- 줌 인 / 줌 아웃
- II. 미세 조정 (정밀한 조작)
- 핑거 스케이팅 / 스케치 (화면에 그리기)
- 토글 여러 개 (on/off 스위치)
- 슬라이더 여러 개
- 버튼 여러 개
- 가속도계 (모바일 기울이기)
- 음성/말
- 의미적: Speech-to-Text (무슨 말을 하는가)
- 비의미적: 음량 (얼마나 크게 말하는가)
- 카메라 트래킹 (시선 추적, 사물 인식)
- 오브젝트 회전 & 확대/축소
2. 멀티 디바이스 인터랙션
- 멀티 디바이스 인터랙션: 기기를 두 대 이상 함께 쓰는 인터랙션
- 예: 모바일은 입력, 스크린/노트북은 출력
- 예: 반포자이즘. 모바일 여러 대 (입력) → 미디어월 1대 + 세로형 TV 3대 (출력)
단일 디바이스 vs. 멀티 디바이스
- 단일 디바이스 (예: 노트북 한 대)
- 구조: 사용자 입력 (마우스/키보드) → 파라미터 변환 → 시각 출력
- 입력: 마우스를 누르고 있는 시간, 마우스가 움직이는 속도와 경로, 키보드 타이핑 속도.
- 예술적 전략: "낯설게 하기" (Verfremdungseffekt). 타이핑 같은 평범한 인터랙션에서 예상 밖의 결과가 나오게 한다.
- 멀티 디바이스 웹 아트워크 (이 수업의 초점)
- 입력 디바이스: 모바일 (iOS / Android)
- 출력 디바이스: 노트북 (1920 x 1080 화면)
- 왜? 모바일의 인터랙션(터치, 기울이기)은 노트북의 인터랙션(마우스, 키보드)과 현상학적으로 느낌이 다르다.
나만의 '비주얼 악기' 만들기
- 프로젝트를 설계할 때 뼈대가 되는 구조다.
- 흐름: 모바일 입력 → 파라미터 변환 + 시스템 규칙 → 노트북 출력
- 어떤 입력을 쓸까? (모바일)
- 버튼 '탭'
- 손가락 '스와이프'
- 줌, 핀치, 회전
- 음성 입력, 카메라 입력
- TTS/STT (Text-to-Speech, Speech-to-Text)
- LLM (AI에 프롬프트 보내기)
- 데시벨 (소리 크기)
- 외부 데이터 (날씨, 교통, 주가)
- 어떤 출력을 쓸까? (노트북)
- 크리에이티브 코딩 (, )
- 텍스트 / 타이포그래피 (폰트, 크기, 레이아웃 바꾸기)
- 이미지 / 영상 콜라주
- 3D 그래픽 (예: )
- 오디오 (예: )
3. Socket.io
- : 클라이언트와 서버가 실시간으로 양방향 통신하는 방식. 웹에서 기기끼리 실시간으로 인터랙션할 수 있게 해준다
- : WebSocket을 쓰기 쉽게 감싼 Javascript 라이브러리. 입문자가 쓰기 좋다 (자동 재연결, fallback 기본 제공)
- 방식
- 클라이언트 A(인터랙션 입력)와 클라이언트 B(인터랙션 출력)가 있다고 하자
- 클라이언트 A가 메시지를 보낸다 → relay 서버가 같은 room에 있는 나머지 클라이언트 모두에게 전달한다 → 클라이언트 B가 받는다
- 템플릿에 이미 설치되어 있다:
socket.io(서버),socket.io-client(브라우저)
이 레포에서의 구조
-
socket-server.mjs: relay 서버. 파일 하나로 되어 있고 4000번 포트를 쓴다join(room): 기기가 room에 들어간다message({ type, data }): 같은 room에 있는 나머지 기기 모두에게 그대로 전달된다- Next.js에 포함된 것이 아니라 따로 실행되는 Node 프로세스다 (그래서 Vercel에는 올릴 수 없다. §7 참고)
-
hooks/shared/useSocket.ts: 클라이언트 쪽 hookconst { send, connected } = useSocket(room, onMessage)send(type, data): room에 메시지를 보낸다onMessage(type, data): 다른 기기에서 메시지가 올 때마다 호출된다- 주소:
NEXT_PUBLIC_SOCKET_URL이 설정되어 있으면 그 주소, 없으면 현재 호스트의 4000번 포트
-
실험 하나의 라우트 구성 규칙
- 두 페이지 모두 같은 room 이름으로
useSocket("<name>", ...)을 호출한다
파일 주소 클라이언트 A · 모바일 app/experiments/w2/<name>/mobile/page.tsxlocalhost:3000/experiments/w2/name/mobile 클라이언트 B · 스크린 app/experiments/w2/<name>/screen/page.tsxlocalhost:3000/experiments/w2/name/screen - 두 페이지 모두 같은 room 이름으로
전체 흐름
다이어그램의 번호 다섯 개는 다음과 같다.
- 스크린 페이지를 연다.
useSocket("drawing", onMessage)가 relay에 연결하고 room에 들어간다 - 모바일 페이지를 연다. 스크린과 마찬가지다
- 모바일:
send("move", { x, y }) - Relay:
{ type: "move", data: { x, y } }를 room의 나머지 기기에 전달한다 - 스크린:
onMessage("move", { x, y })가 호출된다. state를 업데이트하고 화면에 그린다
- 여기까지가 기본 코드다. 이 위에 더 복잡한 기능을 얹거나 모듈로 나눠도 된다
- 기기 사이에 어떤 사변적(speculative) 인터랙션을 만들 것인가? 이 기술을 인터랙티브/몰입형 오디오비주얼 디자인 작업에 어떻게 쓸 것인가?
- Socket.io/WebSocket은 TouchDesigner나 Unreal과도 연결할 수 있다 (W3)
4. Socket.io 예제
이 레포에 있는 예제 (/experiments/w2)
- Drawing: 모바일에서 손가락을 움직인다 → 스크린에 선이 그려진다 (mobile · screen)
- Signature
- Typing: 모바일에서 글을 입력한다 → 그 문장이 채팅 앱 여덟 개에 전송되고, 채팅방마다 답장이 온다 (mobile · screen)
- 3D (Three.js)
- Rotate: 모바일에서 드래그한다 → 스크린의 3D 도형이 회전한다 (mobile · screen)
- Particles: 모바일에서 두 손가락을 벌린다 → 구가 파티클 40,000개로 부서진다 (mobile · screen)
- Togglers: 모바일에서 스위치 40개 위를 핑거 스케이팅한다 → 수면 시뮬레이션 속 파원 40개 (mobile · screen)
- City: 모바일의 세 가지 모드(Settings, Navigate, Statistics) → 생성된 도시의 파라미터, 카메라, 통계. 실시간 사운드 포함 (mobile · screen)
XD Lab 작업
5. 모바일 HTTPS 디버깅
- 모바일 디버깅: 어렵다
- 크로스 디바이스 (모바일 + 데스크톱) 디버깅: 훨씬 더 어렵다
A1. 로컬 네트워크로 접속하기
노트북에서 띄운 페이지를 모바일에서 연다. pnpm dev는 계속 켜둔다.
localhost는 "지금 이 기기"를 뜻한다. 노트북에서 localhost:3000은 노트북을 가리킨다. 모바일에서 localhost를 입력하면 모바일 자신을 가리키는데, 모바일에서는 아무것도 실행되고 있지 않다- 그래서 모바일에는 같은 Wi-Fi 안에서 노트북을 가리키는 주소, 즉 IP 주소가 필요하다. IP 주소는 Wi-Fi 공유기가 기기마다 하나씩 나눠준다. 192.168.0.12나 10.0.0.12 같은 형태다
- 노트북의 IP 주소를 찾는 방법은 두 가지다
- 터미널에서 찾기
- macOS 또는 Linux:
ifconfig | grep "inet " - Windows:
ipconfig - 192.168.x.x나 10.x.x.x 형태의 주소를 쓴다. 127.0.0.1은 localhost이므로 아니다
- macOS 또는 Linux:
- AI 에이전트에게 묻기: "내 컴퓨터의 로컬 IP 주소가 뭐야?" 에이전트가 명령어를 실행해서 알려준다
- 터미널에서 찾기
- 모바일과 노트북을 같은 Wi-Fi에 연결한다. 학교 Wi-Fi가 기기끼리의 통신을 막고 있으면 모바일 핫스팟을 쓴다
- 모바일 브라우저에
http://<YOUR_IP>:3000과 경로를 입력한다. 예: http://192.168.0.12:3000/experiments/w2/drawing/mobile - 노트북에서는 평소처럼 스크린 페이지를 연다: localhost:3000/experiments/w2/drawing/screen
A2. 로컬 개발용 : pnpm dev:mobile
왜 HTTPS가 필요한가
http://: 페이지와 브라우저가 주고받는 내용이 암호화되지 않는다. 같은 네트워크에 있으면 누구나 읽을 수 있다https://: 내용이 암호화된다. 페이지와 브라우저만 읽을 수 있다- 카메라, 마이크, 모션 센서에는 사용자의 모습과 지금 있는 공간이 그대로 담긴다. 그래서 브라우저는
https://로 연 페이지에서만 이 기능을 쓰게 해준다 - 예외가 하나 있다.
localhost다. localhost에서는 아무것도 내 기기 밖으로 나가지 않는다. W1에서pnpm dev만으로 노트북 카메라를 쓸 수 있었던 이유다 - 모바일은
http://192.168.x.x로 페이지를 연다. localhost도 아니고 https도 아니다. 그래서 페이지를 https로 띄우기 전까지는 카메라와 센서가 막힌다
방법
- 실행 중인 서버를 끈다.
pnpm dev를 실행한 터미널에서Ctrl + C를 누른다 pnpm dev:mobile로 다시 켠다. 서버 두 개(3000, 4000)는 그대로이고 이번에는 https로 뜬다. 처음 실행할 때는 비밀번호를 물어볼 수 있다. 모바일에서 열 주소가 출력된다- 모바일에서
https://<YOUR_IP>:3000과 경로를 연다. 경고 페이지가 뜬다 ("연결이 비공개로 설정되어 있지 않습니다")- 정상이다. 인증서는 "이 사이트가 진짜 그 사이트가 맞다"는 것을 증명하는데, 이 인증서를 내 노트북이 직접 만들었기 때문에 모바일이 확인할 수 없다
- "고급" → **"계속 진행 (안전하지 않음)"**을 누른다
- relay도 똑같이 해준다. 모바일에서
https://<YOUR_IP>:4000을 열고 경고를 넘어간다. "socket relay ok"가 보여야 한다- 이 단계를 건너뛰면 페이지는 열리지만 스크린에는 아무것도 전달되지 않는다
- 노트북에서는 https://localhost:3000을 연다
경고는 기기마다 한 번만 넘어가면 된다.
A3. 원격 디버깅 (iOS vs. Android)
모바일의 console.log() 메시지, DOM, 네트워크 요청을 컴퓨터 화면에서 확인한다.
Android (Chrome 디버깅)
- Android 기기에서: "개발자 옵션"을 켠다 (보통 숨겨져 있으므로 본인 기종에서 켜는 방법을 검색한다). 개발자 옵션에서 "USB 디버깅"을 켠다.
- 컴퓨터에서: 모바일을 USB 케이블로 컴퓨터에 연결한다.
- 데스크톱 Chrome을 열고 주소창에
chrome://inspect#devices를 입력한다. - 연결한 기기와 열려 있는 탭이 보인다. 디버깅할 탭의 "Inspect"를 누른다.
- DevTools 창이 열리고, 모바일 브라우저를 여기서 검사할 수 있다.
iOS (Safari Web Inspector)
참고: Mac이 있어야 한다.
- iPhone에서: 설정 > Safari > 고급으로 들어가 "웹 속성(Web Inspector)"을 켠다.
- Mac에서: Safari를 연다. Safari > 설정 > 고급으로 들어가 맨 아래의 "메뉴 막대에서 개발자용 메뉴 보기"를 체크한다.
- 연결: iPhone을 USB 케이블로 Mac에 연결한다.
- Mac의 Safari에 새로 생긴 "개발자용" 메뉴를 누른다. iPhone 이름이 보인다.
- iPhone 이름에 마우스를 올리면 열려 있는 탭 목록이 나온다. 디버깅할 탭을 누르면 Web Inspector 창이 열린다.
6. 모바일 센서
- 카메라, 마이크, 모션 센서는 (또는 localhost)에서만 작동한다:
pnpm dev:mobile(A2) - 사용자가 탭한 뒤에 시작된다. 브라우저가 권한을 묻는다
| 입력 | 브라우저 API | 예제 | |
|---|---|---|---|
| 기울기 | deviceorientation 이벤트 → alpha, beta, gamma (도) | w2/tilt | |
| 흔들기 | devicemotion 이벤트 → acceleration | ||
| 마이크 | navigator.mediaDevices.getUserMedia({ audio: true }) | w1/video | |
| 카메라 | navigator.mediaDevices.getUserMedia({ video: true }) | w2/camera-slit-scan · w1/glsl/creation-webcam |
기울기 (가속도계)
- iOS: 탭 핸들러 안에서
DeviceOrientationEvent.requestPermission()을 호출한다. Android: 권한 팝업이 없다
async function start() {
// iOS만: 권한 요청 (탭 안에서 불러야 한다)
const eventClass = DeviceOrientationEvent as unknown as { requestPermission?: () => Promise<string> };
if (eventClass.requestPermission) await eventClass.requestPermission();
window.addEventListener("deviceorientation", (event) => {
const x = (event.gamma ?? 0) / 45; // 좌 / 우
const y = (event.beta ?? 0) / 45; // 앞 / 뒤
send("tilt", { x, y });
});
}
- 전체 코드:
app/experiments/w2/tilt/
예제 (HTTPS)
7. Socket 배포
- W1 §12에서 한 배포는 내 노트북(localhost)에서만 열리던 앱을 에 올려서 누구나 접속할 수 있게 만드는 일이었다
- 멀티 디바이스 작업은 프로그램 두 개가 같이 돌아야 한다(§3). Next.js 앱(3000 포트)과 relay 서버
socket-server.mjs(4000 포트)다 - 이 중에서 Vercel에 올릴 수 있는 것은 Next.js 앱뿐이다. relay 서버는 올릴 수 없다
- Vercel은 serverless 방식이라, 누군가 페이지를 열 때만 잠깐 코드를 실행하고 곧바로 종료한다
- 반면 relay 서버는 모바일, 스크린과 연결을 계속 유지해야 해서 꺼지면 안 된다
- 따라서 relay 서버를 계속 켜둘 컴퓨터가 따로 있어야 한다. 방법은 두 가지다
1. 내 노트북에서 돌리기
- 수업 시간에 쓴 방식이다.
pnpm dev(또는pnpm dev:mobile)를 실행하면 두 프로그램이 노트북에서 함께 돌고, 모바일은 같은 Wi-Fi로 접속한다(§5) - 따로 배포할 필요는 없지만, 같은 Wi-Fi에 연결된 기기에서만 열린다
2. 인터넷 서버에 올리기
- Next.js 앱은 W1 때처럼 Vercel에 올리고, relay 서버는 프로그램을 계속 켜둘 수 있는 호스팅 서비스에 올린다. 나 를 쓴다
- 도 한 예다. 반포자이즘의 relay 서버가 여기서 돌아간다
- 이렇게 하면 같은 Wi-Fi가 아니어도, 주소만 알면 어디서든 작업을 열 수 있다
- Black Room에서 진행하는 기말 프로젝트는 이 방식으로 배포하기를 권장한다
앱에 relay 서버 주소 알려주기
- 노트북에서는 앱과 relay 서버가 같은 컴퓨터에 있었다. 그래서 주소를 따로 알려주지 않아도 페이지가 "지금 이 컴퓨터의 4000 포트"로 접속하면 됐다
- 배포하고 나면 둘이 서로 다른 곳에 있게 된다. 앱은 Vercel에, relay 서버는 Render에 있고 주소도 각각 다르다. 앱은 relay 서버가 어디에 있는지 모르기 때문에 주소를 직접 알려줘야 한다
- 주소는 Vercel의 환경 변수(Environment Variable)로 알려준다. 환경 변수는 코드에 직접 적지 않는 값이다. 서비스의 설정 화면에 "이름 = 값" 형태로 적어두면 앱이 그 값을 읽어서 쓴다
- 이름:
NEXT_PUBLIC_SOCKET_URL. 이 템플릿의useSocket은 이 이름으로 relay 서버 주소를 찾는다 - 값: Render가 만들어 준 relay 서버 주소. 예를 들면
https://my-relay.onrender.com
- 이름:
Render로 배포하기
- Next.js 앱: 레포를 GitHub에 push한 뒤 Vercel에 배포한다 (W1 §12)
- relay 서버: https://render.com → 가입 → + New > Web Service → 앱을 올린 것과 같은 GitHub 레포 선택 → Connect
- 설정 항목을 아래와 같이 입력한다. Start Command에 적은 명령 때문에 이 서비스는 Next.js 앱이 아니라 relay 서버를 실행하게 된다
- Language:
Node - Build Command:
pnpm install - Start Command:
node socket-server.mjs - Compute:
Free - Environment Variables:
NODE_VERSION=24
- Language:
- 배포가 끝나면 Render가 relay 서버의 주소(
https://<name>.onrender.com)를 만들어 준다. 이 주소를 열었을 때 "socket relay ok"가 보이면 정상이다 - 이 주소를 Vercel에 환경 변수로 등록한다
- Vercel에서 내 프로젝트를 연다 → Settings → Environment Variables
- Key에
NEXT_PUBLIC_SOCKET_URL, Value에https://<name>.onrender.com을 입력하고 Save를 누른다 - 다시 배포한다. Deployments → 가장 최근 배포의 ⋯ → Redeploy. 환경 변수는 배포할 때 앱에 들어가기 때문에, 다시 배포해야 적용된다
- Vercel 주소로 접속해서 노트북에서는
/screen, 모바일에서는/mobile을 연다
- 무료 플랜에서는 15분 동안 접속이 없으면 relay 서버가 꺼진다. 그 뒤 처음 접속할 때는 다시 켜지느라 1분 정도 걸린다
- 문서: Your first deploy · WebSockets · Free plan
Railway로 배포하기
- Next.js 앱: 위와 똑같이 Vercel에 배포한다
- relay 서버: https://railway.com → GitHub 계정으로 가입 → New Project → GitHub repo → 같은 레포 선택
- 서비스 → Settings → Custom Start Command에
node socket-server.mjs입력 → Deploy - 서비스 → Settings → Networking → Generate Domain. 만들어진 주소
https://<name>.up.railway.app을 열었을 때 "socket relay ok"가 보이면 정상이다 - 이 주소를 Vercel에 환경 변수로 등록한다. 위 5번과 같고, Railway 주소를 넣으면 된다
- 무료 체험은 크레딧 $5, 30일까지다. 그 이후에는 월 $5를 낸다
- 문서: Quick start · Build and start commands · Domains
8. 과제: 웹 과제 2
모바일과 노트북을 연결한 인터랙티브 경험 만들기. 마감은 Web 3 (11/16).