這是入門版,進階版可以參考這裡 http://lolikitty.pixnet.net/blog/post/205684867
import java.io.*;
import java.net.*;
public class MyServer {
public static void main(String[] args) {
try {
ServerSocket ss = new ServerSocket(1024);
Socket s = ss.accept();
BufferedReader buf = new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintWriter w = new PrintWriter(new OutputStreamWriter(s.getOutputStream()), true);
String msg;
int i = 0;
while ((msg = buf.readLine()) != null) {
System.out.println("接收到的資料是:" + msg);
w.println("OK 哈哈哈 " + i++);
}
s.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
using UnityEngine;
using System.Collections;
using System;
using System.Net.Sockets;
using System.IO;
using System.Net;
using System.Text;
public class MyClient : MonoBehaviour
{
StreamWriter sw = null;
TcpClient tc = null;
NetworkStream ns = null;
StreamReader sr = null;
int i = 0 ;
void OnGUI ()
{
if (GUILayout.Button ("Init")) {
tc = new TcpClient ("127.0.0.1", 1024);
ns = tc.GetStream ();
sw = new StreamWriter (ns);
sr = new StreamReader (ns);
}
if (GUILayout.Button ("Send")) {
sw.WriteLine ("Hello~ " + i++);
sw.Flush ();
print (sr.ReadLine ());
}
}
}
全站熱搜
留言列表