2015年3月31日 星期二

TCP: Server / Client

Java (Server):

package server;

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 java.util.Date;
  

public class Server  implements Runnable {
      private Socket clientSocket;
      Server (){
          ServerSocket ss = null;
          try {
            ss = new ServerSocket(1800);
            System.out.println("[▶] 伺服器已啟動,等待連線中...");
          } catch (IOException e) {
        }

     while (true) {
            try {
                Socket s = ss.accept();
                new Thread(this).start();
            } catch (IOException e) {
            }
       }
    }

    @Override
    public void run() {
        
        InputStreamReader isr = null;
        BufferedReader br = null;
        OutputStreamWriter osw = null;
        PrintWriter wr = null;
        String ip = null;
        
               try {
                System.out.println("------------------------------------------");
                ip = clientSocket.getInetAddress().toString();
                System.out.println("連線IP : " + ip + ":" + clientSocket.getPort());
                System.out.println("連線時間 : " + new Date());
                isr = new InputStreamReader(clientSocket.getInputStream());
                br = new BufferedReader(isr);
                String msg = br.readLine();
                osw = new OutputStreamWriter(clientSocket.getOutputStream());
                wr = new PrintWriter(osw, true);
                System.out.println("傳來的值:" + msg);
               // 遊戲邏輯,對接收到的值之後進行分類,再依需求做處理。
            } catch (IOException e) {
            }
    }
    
        public static void main(String [] args) {
         new Server ();
   }
}

--------------------------------------------------

Client (Unity C#):

using System; 
using System.Net.Sockets; 
using System.IO; 
using UnityEngine;
using System.Collections;

public class TcpClientScript : MonoBehaviour{

Socket socket;
StreamReader sr;

byte[] bate, aaa;

TcpClient tcpClient;
NetworkStream ns;

public void setClinetStart(string ip, int port){

try {

tcpClient = new TcpClient (ip, port);
NetworkStream ns = tcpClient.GetStream (); 
StreamWriter sw = new StreamWriter (ns); 
sw.WriteLine ("Unity C# 傳來的訊息");           
sw.Flush (); 
StreamReader sr = new StreamReader (ns); 
print ("從 Java服務器接收到的訊息:" + sr.ReadLine ());
} catch (Exception e) {
print (e); 
Application.Quit();
}
}
}


沒有留言:

張貼留言