Java Server (會使用 org.json):
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import org.json.JSONObject;
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket ss = new ServerSocket(1024);
System.out.println("伺服器已啟動...");
JSONObject obj = new JSONObject();
while (true) {
Socket s = ss.accept();
new Thread(() -> {
String ip = null;
try {
JSONObject data = new JSONObject();
ip = s.getRemoteSocketAddress().toString();
obj.put(ip, data);
System.out.println("我的 IP 是:" + ip);
BufferedReader r = new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintWriter w = new PrintWriter(new OutputStreamWriter(s.getOutputStream()), true);
data.put("Name", r.readLine());
data.put("Socket", s);
//------------------------------- Message
String msg = null;
while ((msg = r.readLine()) != null) {
System.out.println(msg);
for (String cip : obj.keySet()) {
JSONObject jobj = (JSONObject) obj.get(cip);
Socket cs = (Socket) jobj.get("Socket");
PrintWriter pw = new PrintWriter(new OutputStreamWriter(cs.getOutputStream()), true);
pw.println(msg);
}
}
} catch (Exception e) {
System.out.println(e);
}
obj.remove(ip);
System.out.println(obj.toString(4));
System.out.println("Close");
}).start();
}
}
}
Unity :
using UnityEngine;
using System.Collections;
using System;
using System.Net.Sockets;
using System.IO;
using System.Net;
using System.Text;
using System.Threading;
public class MyClient : MonoBehaviour
{
StreamWriter sw = null;
TcpClient tc = null;
NetworkStream ns = null;
StreamReader sr = null;
int i = 0 ;
string name = "";
string data = "";
string msg = "";
void OnGUI ()
{
GUI.Label (new Rect(10, 10, 100, 20), "Name");
name = GUI.TextField (new Rect(50, 10, 100, 20), name, 25);
if (GUI.Button (new Rect(10, 40, 100, 20), "Connect")) {
tc = new TcpClient ("127.0.0.1", 1024);
ns = tc.GetStream ();
sw = new StreamWriter (ns);
sr = new StreamReader (ns);
sw.AutoFlush = true;
sw.WriteLine (name);
new Thread(Read).Start();
}
data = GUI.TextArea (new Rect(10, 80, 200, 200), data);
msg = GUI.TextField (new Rect(10, 300, 200, 20), msg, 25);
if (GUI.Button (new Rect(10, 330, 200, 20), "Send")) {
sw.WriteLine (msg);
data += name + " : " + msg + "\n";
msg = "";
}
}
bool isStart = true;
void Read(){
while(isStart){
string msg = sr.ReadLine ();
data += "Other : " + msg + "\n";
}
}
void OnApplicationQuit(){
isStart = false;
tc.Close ();
sr.Close ();
sw.Close ();
}
}
留言列表