公告版位
需要找什麼嗎? 左邊分類或許可以幫助你...

目前分類:[程式語言] C # (15)

瀏覽方式: 標題列表 簡短摘要

// 先匯入
using System;
using System.Net;
using System.Net.Sockets;
using System.IO;



// 把下面程式碼丟入 Main() 方法裡

try

黃彥霖 發表在 痞客邦 留言(0) 人氣()

using System;
using System.Runtime.InteropServices;

namespace ttt
{
    class MainClass
    {

        [DllImport("user32")]
        static extern bool SetCursorPos(int X, int Y);

黃彥霖 發表在 痞客邦 留言(1) 人氣()

請先匯入:using System.Diagnostics;

 

寫法一:

Process.Start (@"C:\Users\Est\Desktop\GodHand3D\GodHand3D.exe");

 

寫法二:

ProcessStartInfo open = new ProcessStartInfo ();
open.FileName = "GodHand3D.exe"; // 檔案名稱
open.WorkingDirectory = @"C:\Users\Est\Desktop\GodHand3D"; // 資料夾路徑
Process.Start (open);

黃彥霖 發表在 痞客邦 留言(5) 人氣()

    依造個人需求,在使用TCP設計客戶端(Client)時,有時候使用Socket方便;有時候使用TcpClient方便。所以今天我提供2種常使用與容易使用的方式,且不需要事先宣告byte[]來當作緩衝(Buffer),也不需要用迴圈把byte一個一個讀取出來。如此一來可以專心在商業邏輯上,加快程式的選寫速度與維護。

方法一 使用 Socket:

using System;
using System.Net;
using System.Net.Sockets;
using System.IO;

class Program
{
    static void Main(string[] args)
    {
        Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        socket.Connect("61.227.71.237", 1024); // 1.設定 IP:Port 2.連線至伺服器
        NetworkStream stream = new NetworkStream(socket);
        StreamReader sr = new StreamReader(stream);
        StreamWriter sw = new StreamWriter(stream);
        
        sw.WriteLine("你好伺服器,我是客戶端。"); // 將資料寫入緩衝
        sw.Flush(); // 刷新緩衝並將資料上傳到伺服器

        Console.WriteLine("從伺服器接收的資料: " + sr.ReadLine());
        
        Console.ReadLine();
    }
}

方法二 使用 TcpClient :

using System;
using System.Net;
using System.Net.Sockets;
using System.IO;

class Program
{
    static void Main(string[] args)
    {
        TcpClient tcp = new TcpClient("61.227.71.237", 1024); // 1.設定 IP:Port 2.連線至伺服器
        NetworkStream stream = new NetworkStream(tcp.Client);
        StreamReader sr = new StreamReader(stream);
        StreamWriter sw = new StreamWriter(stream);

        sw.WriteLine("你好伺服器,我是客戶端。"); // 將資料寫入緩衝
        sw.Flush(); // 刷新緩衝並將資料上傳到伺服器

        Console.WriteLine("從伺服器接收的資料: " + sr.ReadLine());

        Console.ReadLine();
    }
}

 

 

 


黃彥霖 發表在 痞客邦 留言(0) 人氣()

// 本範例不適合用於對稱行網路,要解決此問題請先讓 Client 連線至 Server ,讓 Client 知道自己的 (公開/內部 IP ) 與其他人的 (公開/內部 IP ) ,再檢查自己公開 IP 是否與其他人的公開 IP 重複,如果有重複代表自己處於對稱行網路中,將使用內部 IP 進行通訊即可。

 Java 伺服器程式碼:

 

 package javaapplication1;

import java.net.*;
import java.util.ArrayList;
import java.util.HashMap;

public class JavaApplication1 {

    public static void main(String[] args) throws Exception {
        byte[] buffer = new byte[65507];
        DatagramPacket dp = new DatagramPacket(buffer, buffer.length);
        DatagramSocket ds = new DatagramSocket(5555); // Set Server Port
        System.out.println("伺服器啟動於 : "
                + InetAddress.getLocalHost().getHostAddress() + ":" + ds.getLocalPort());
        String msg = "No Message...";
        HashMap map = new HashMap();
        while (true) {
            dp = new DatagramPacket(buffer, buffer.length);
            ds.receive(dp);
            msg = new String(dp.getData(), 0, dp.getLength());

            String ipPort = dp.getAddress().getHostAddress() + ":" + dp.getPort();
            // 只要一連線就會把 IP 放進 map 裡
            map.put(ipPort, "");
            System.out.println(ipPort + " 傳來的訊息 : " + msg);

            // 回傳他們自己的 外網IP
            dp = new DatagramPacket(ipPort.getBytes(), ipPort.length(), dp.getAddress(), dp.getPort());
            ds.send(dp);


            // 如果 2 個人上線了...
            if (map.size() == 2) {
                ArrayList a = new ArrayList();
                for (Object ip_Port : map.keySet()) {
                    a.add(ip_Port.toString());
                }
                for (Object ip_Port : map.keySet()) {
                    String temp = "";
                    for (int i = 0; i < a.size(); i++) {
                        // 如果現在這個IP不等於之前存放在 map 裡的IP
                        // 簡單來說就是只要獲取對方的IP,並不需要用到自己的IP
                        if (!a.get(i).equals(ip_Port)) {
                            temp += a.get(i);
                        }
                    }
                    // 為每個連線端發送對方的 IP:Port
                    dp = new DatagramPacket(temp.getBytes(), temp.length(), getIP(ip_Port), getPort(ip_Port));
                    ds.send(dp);
                }
            }
        }
    }

    static InetAddress getIP(Object ipPort) throws UnknownHostException {
        return InetAddress.getByName(ipPort.toString().split(":")[0]);
    }

    static int getPort(Object ipPort) {
        return Integer.valueOf(ipPort.toString().split(":")[1]);
    }
}

 

 C# 客戶端程式碼:

 

 using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;


class MyClient
{
    public static UdpClient uc = null;
    public static IPEndPoint otherIP = null;

    static void Main(string[] args)
    {
        // 伺服器的 IP 與 Port
        IPEndPoint servrIP = new IPEndPoint(IPAddress.Parse("122.121.9.25"), 5555);
        // 自訂要監聽的 Port
        IPEndPoint myIP = new IPEndPoint(IPAddress.Any, 4444);
        uc = new UdpClient(myIP.Port);
        string receive;
        byte[] b;

        // 向伺服器傳資料:
        b = System.Text.Encoding.UTF8.GetBytes("Hello Server");
        uc.Send(b, b.Length, servrIP);

        // 從伺服器取得目前電腦的IP:
        string myPublicIP = System.Text.Encoding.UTF8.GetString(uc.Receive(ref servrIP));
        Console.WriteLine("目前電腦的IP:" + myPublicIP);
        Console.WriteLine("\n|-----------------------------------|\n");

        // 從伺服器取得對方IP:
        receive = System.Text.Encoding.UTF8.GetString(uc.Receive(ref servrIP));
        otherIP = new IPEndPoint(IPAddress.Parse(receive.Split(':')[0]), int.Parse(receive.Split(':')[1]));

        // 打洞:
        b = System.Text.Encoding.UTF8.GetBytes("Hi");
        uc.Send(b, b.Length, otherIP);

        // 為監聽{uc.Receive()}建立一條執行緒:
        // ( 1.接收/2.發送 兩種功能建議個別建立執行緒
        // 如果沒有建立執行緒程式可能會鎖死 )
        new Thread(new MyReceiveThreadClass().MyRun).Start();

        // 傳送真正的資料:
        int i = 0;
        while (true)
        {
            b = System.Text.Encoding.UTF8.GetBytes("這是 " + myPublicIP + " 資料 : " + i++);
            uc.Send(b, b.Length, otherIP);
            //Thread.Sleep(1000);
        }
    }
}

class MyReceiveThreadClass
{
    public void MyRun()
    {
        while (true)
        {
            string receive = System.Text.Encoding.UTF8.GetString(MyClient.uc.Receive(ref MyClient.otherIP));
            Console.WriteLine(receive);
        }
    }
}

 

  伺服器輸出結果:

 ccccccccccccccccc  

 

黃彥霖 發表在 痞客邦 留言(5) 人氣()

    這邊主要的重點是 UdpClient 這個類別,雖然從字面上這個類別叫做 UDP 的 Client (客戶端),但實際上我們也可以用它來建立伺服器,簡單來說 UdpClient 類別可以同時建立 伺服器端 (Server) 與 客戶端 (Client) 兩種功能

    如果今天要建立伺服器端 UdpClient 則要宣告成 UdpClient uc = new UdpClient(5555); ,這裡的 5555 代表伺服器的 Port (監聽埠)。

    如果今天要建立客戶端 UdpClient 擇要宣告成 UdpClient uc = new UdpClient(); ,也就是不需要指定 Port,因為只是發送消息,並不是要接收,所以電腦會依流水號的方式分配Port,將資料傳到指定IP:Port上 (此時指定IP:Port是使用 IPEndPoint 類別)。

以下範例程式碼:

 

伺服器端:

 using System;
using System.Net;
using System.Net.Sockets;

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("這是伺服器...\n");

        IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 5555);
        UdpClient uc = new UdpClient(ipep.Port);

        int i = 0;
        while (true)
        {
            Console.WriteLine(System.Text.Encoding.UTF8.GetString(uc.Receive(ref ipep)));
            byte[] b = System.Text.Encoding.UTF8.GetBytes("這是'伺服器'回傳的訊息 ~ " + i++);
            uc.Send(b, b.Length, ipep);
        }
    }
}

客戶端:

using System;
using System.Net;
using System.Net.Sockets;

class MainClass
{
        public static void Main (string[] args)
        {
                Console.WriteLine ("這是客戶端...\n");
                IPEndPoint ipep = new IPEndPoint (IPAddress.Parse ("127.0.0.1"), 5555);
                UdpClient uc = new UdpClient ();
            
                for (int i = 0; i<10; i++) {
                        byte[] b = System.Text.Encoding.UTF8.GetBytes ("這是'客戶端'傳送的訊息 ~ " + i);            
                        uc.Send (b, b.Length, ipep);
                        Console.WriteLine (System.Text.Encoding.UTF8.GetString (uc.Receive (ref ipep)));
                }                       
        }
}


執行結果:

aaa

黃彥霖 發表在 痞客邦 留言(0) 人氣()

dfsdfs  

參考COM - Shockwave Flash

在工具箱按滑鼠右鍵選[選擇項目] COM元件 Shockwave Flash Object
然後再將元件拉到表單上


using System; 
using System.Collections.Generic; 
using System.ComponentModel; 

黃彥霖 發表在 痞客邦 留言(0) 人氣()

顧名思意,String 類別就是來處理字串的應用 
它提供了一堆靜態方法 (Static Method) 來處理字串相關 
以下介紹一些平時很實用的功能

字串的比較
Compare 方法會回傳整數值,來表示兩個字串的關聯性 
正數表示第一個字串大於第二個字串 
負數表示第一個字串小於第二的字串 
零值表示兩個字串相等 
string.Compare("字串", "測試"); // result = -1 

黃彥霖 發表在 痞客邦 留言(1) 人氣()

第一种方法:
            string s = "abcdeabcdeabcde";
            string[] sArray = s.Split('c');
            foreach (string i in sArray)
                Console.WriteLine(i.ToString());
            Console.ReadKey();
输出下面的结果:
ab
deab
deab

黃彥霖 發表在 痞客邦 留言(0) 人氣()

// 伺服器程式碼 -------------------------------------------------------------------------------
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
 
namespace g
{
    class MainClass
    {

黃彥霖 發表在 痞客邦 留言(0) 人氣()

using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace ServerSocket
{
class ServerSocket
{
public static ManualResetEvent thread = new System.Threading.ManualResetEvent(false);

/// 應用程式的主進入點

黃彥霖 發表在 痞客邦 留言(0) 人氣()

加入這一行即可強制關閉程式 :

System.Environment.Exit(System.Environment.ExitCode);

 


黃彥霖 發表在 痞客邦 留言(1) 人氣()

using System.Timers;

public static void Main (string[] args){

    System.Timers.Timer t = new System.Timers.Timer(1000);
    t.Elapsed += new ElapsedEventHandler(run);
    t.Enabled = true;

}

 

public static void run(object source,System.Timers.ElapsedEventArgs e){

    Console.WriteLine("OK");

黃彥霖 發表在 痞客邦 留言(0) 人氣()

Socket cli;

while(true){

    // 接收到的資料

    byte [] b = new byte[1024];

    int i = cli.Receive(b, 0, b.Length, SocketFlags.None);

 

    // 傳送的資料

    byte[] msg = Encoding.ASCII.GetBytes("ABCD");

    int bytesSend = cli.Send(msg, 0, msg.Length, SocketFlags.None);

黃彥霖 發表在 痞客邦 留言(0) 人氣()

using System;

namespace c  // 在 c 資料夾
{
    class MainClass
    {
        public static void Main (string[] args)
        {

            Console.Write ("請輸入一個字元");
            Console.WriteLine (" u 碼為:" + Console.Read());

 

黃彥霖 發表在 痞客邦 留言(0) 人氣()