導航:首頁 > 配伺服器 > 套接字客戶端如何連接到伺服器

套接字客戶端如何連接到伺服器

發布時間:2024-04-15 13:20:47

Ⅰ filezilla鎬庝箞榪炴帴filezilla鎬庝箞榪炴帴鏈嶅姟鍣

filezilla錛屾垜鍦ㄥ惰繛涓嶄笂銆

1銆傞栧厛鎵撳紑鎺у埗闈㈡澘涓鐨勨渨indows闃茬伀澧欌濄2銆傜劧鍚庤緭鍏モ滃厑璁哥殑搴旂敤鈥濓紝鐐瑰嚮鍙充笅瑙掔殑鈥滃厑璁稿叾浠栧簲鐢ㄢ濄3銆傜劧鍚庨夋嫨鈥滄坊鍔犲簲鐢ㄢ濇坊鍔犫渇ilezilla鈥濈殑蹇鎹鋒柟寮忋4銆傛坊鍔犲悗錛岃繘鍏filezilla杞浠訛紝鐐瑰嚮鈥滅紪杈戔濊繘鍏モ滆鍔ㄦā寮忚劇疆鈥濄5銆傚嬀閫夆滀嬌鐢ㄤ笅鎷塈P鈥濓紝濉鍐欏師涓繪満鐨処P鍦板潃鍗沖彲瑙e喅闂棰樸

auth榪炴帴涓嶅埌鏈嶅姟鍣錛

鍘熷洜鍒嗘瀽錛

榪欐槸鐢變簬鐩鍓嶈櫄鎷熶富鏈轟笉鏀鎸丗TPoverTLS鐨勮繛鎺ユ柟寮忋侳TPoverTLS鏄鎸囧㈡埛絝鏄懼紡璇鋒眰錛堝㈡埛絝鍙戦丄UTHTLS鍛戒護錛夊笷TP浼氳瘽鍔犲瘑銆傝櫄鎷熶富鏈烘湇鍔″櫒浼氭嫆緇濊鋒眰TLS鐨勮繛鎺ャ

瑙e喅鏂規硶錛

瀹㈡埛鍙浠ヨ劇疆FTP瀹㈡埛絝涓嶈佹眰浼氳瘽鍔犲瘑錛屽嵆閲囩敤鏅閫氱殑FTP浼氳瘽鏂瑰紡銆

浠FileZilla杞浠朵負渚嬶紝瀹㈡埛鍦ㄧ$悊絝欑偣鐨勬椂鍊欙紝鈥滃姞瀵嗏濋夋嫨涓衡滃彧浣跨敤鏅閫欶TP錛堜笉瀹夊叏錛夆濓紝

淇濆瓨絝欑偣淇℃伅涔嬪悗錛屽啀嬈¤繛鎺ヨ櫄鎷熶富鏈烘湇鍔″櫒錛屾祴璇曟垚鍔熴

filezile濡備綍浣跨敤錛

瀹夎呭ソ鍚庢墦寮FileZilla錛屾渶欏朵笂鐨勫氨鏄榪滅▼榪炴帴鍔熻兘錛

涓繪満鍚嶏細sftp://+鏈嶅姟鍣ㄥ叕緗慽p

鐢ㄦ埛鍚嶏細闃塊噷浜戞帶鍒跺彴涓榪滅▼榪炴帴閲岀殑璐﹀彿錛屼竴鑸涓簉oot

瀵嗙爜錛氬垰鍒氬壋寤虹殑閭d釜澶嶆潅鐨勫瘑鐮

絝鍙o細22

鍗曞嚮蹇閫熼摼鎺ユ寜閽錛屽嵆鍙榪炴帴鍒拌嚜宸辯殑鏈嶅姟鍣ㄣ

filezill浣跨敤鏁欑▼錛

filezilla鐨勪嬌鐢ㄦ柟娉曪細棣栧厛涓嬭澆瀹夎呭苟鍚鍔‵ileZilla杞浠訛紱鐒跺悗灝嗚璦鍒囨崲鑷充腑鏂囷紱

鎺ョ潃渚濇$偣鍑燴淓dit-Settings-Language-Chinese鈥濋」騫墮噸鍚錛

鏈鍚庣偣鍑燴滄柊寤虹珯鐐光濆苟榪涜岃繙紼嬭繛鎺ュ嵆鍙銆

鎵嬫満浣跨敤FTP錛屽備綍璁劇疆鎵嶈兘榪炴帴涓婁紶紼嬪簭錛

鎵嬫満涓婄敤app寮FTP鏈嶅姟錛岀劧鍚庝粠鐢佃剳絝閫氳繃FTP瀹㈡埛絝錛堟瘮濡侳ilezilla錛夎繛鍒版墜鏈虹殑IP鍦板潃鍜岀鍙e氨鍙浠ヨ塊棶鎵嬫満鐨勬暟鎹浜嗭紝涔熷彲浠ヤ笂浼犳枃浠跺埌鎵嬫満/浠庢墜鏈轟笅杞芥枃浠躲

鎵嬫満涓婂紑FTP錛屽簲鐢ㄥ晢搴楅噷搴旇ヤ竴鎶撲竴澶ф妸銆傛垜涔嬪墠鐢‥S鏂囦歡綆$悊鍣錛屾浘緇忓緢鏈夊悕鐨勶紝浣嗘槸鐜板湪鍙堟參鏈夎噧鑲匡紝騫垮憡榪樹竴澶у爢銆

鎬庝箞浣跨敤FTP涓婁紶鏂囦歡錛

鏈夋椂鍊欐垜浠闇瑕佷笂浼犳枃浠跺埌鉶氭嫙涓繪満鎴栬呬簯鏈嶅姟鍣ㄤ腑錛屼笅闈㈡潵緇欏ぇ瀹朵粙緇嶄竴涓嬫庝箞鎿嶄綔

宸ュ叿/鍘熸枡

FileZilla

鏂規硶/姝ラ

1銆佺偣鍑繪枃浠舵寜閽

2銆佺偣鍑葷珯鐐圭$悊鍣

3銆佺偣鍑繪柊絝欑偣鎸夐挳

4銆佸湪鍙充晶杈撳叆瑕佽繛鎺ョ殑涓繪満鍚

5銆佺鍙e彲浠ヤ笉濉榛樿ゆ槸21絝鍙

6銆佽緭鍏ftp鐢ㄦ埛鍚

7銆佺偣鍑昏繛鎺ユ寜閽

8銆佽緭鍏ュ瘑鐮佸悗鐐瑰嚮紜瀹氭寜閽鍗沖彲

Ⅱ 鏈夎皝鑳界粰鎴戞濊礬鍚楋紵 鍏充簬綆鍗曠殑socket緙栫▼銆

棣栧厛錛屼綘寰楀啓涓鏈嶅姟鍣錛涚敤涓や釜瀹㈡埛絝榪炴帴涓婃湇鍔″櫒錛屽㈡埛絝閫氳繃鏈嶅姟鍣ㄨ繘琛屾暟鎹浜ゆ祦銆

鍩轟簬TCP錛堥潰鍚戣繛鎺ワ級鐨凷ocket緙栫▼
鏈嶅姟鍣ㄧ欏哄簭錛
1. 鍔犺澆濂楁帴瀛楀簱
2. 鍒涘緩濂楁帴瀛楋紙socket錛
3. 灝嗗楁帴瀛楃粦瀹氬埌涓涓鏈鍦板湴鍧鍜岀鍙d笂錛坆ind錛
4. 灝嗗楁帴瀛楄句負鐩戝惉妯″紡錛屽噯澶囨帴鏀跺㈡埛璇鋒眰錛坙isten錛
5. 絳夊緟瀹㈡埛璇鋒眰鐨勫埌鏉ワ紱褰撹鋒眰甯︽潵鍚庯紝鎺ュ彈榪炴帴璇鋒眰錛岃繑鍥炰竴涓鏂扮殑瀵瑰簲浜庢ゆ¤繛鎺ョ殑濂楁帴瀛楋紙accept錛
6. 鐢ㄨ繑鍥炵殑濂楁帴瀛楀拰瀹㈡埛絝榪涜岄氫俊錛坰end/recv錛
7. 榪斿洖錛岀瓑寰呭彟涓涓瀹㈡埛璇鋒眰
8. 鍏抽棴濂楁帴瀛(closesocket)
瀹㈡埛絝紼嬪簭錛
1. 鍔犺澆濂楁帴瀛楀簱
2. 鍒涘緩濂楁帴瀛(socket)
3. 鍚戞湇鍔″櫒鍙戦佽繛鎺ヨ鋒眰錛坈onnect錛
4. 鍜屾湇鍔″櫒絝榪涜岄氫俊(send/receive)
5. 鍏抽棴濂楁帴瀛(closesocket)

鍩轟簬UDP錛堥潰鍚戞棤榪炴帴錛夌殑socket緙栫▼
鏈嶅姟鍣ㄧ錛堟帴鏀剁錛夌▼搴忥細
1. 鍔犺澆濂楁帴瀛楀簱
2. 鍒涘緩濂楁帴瀛楋紙socket錛
3. 灝嗗楁帴瀛楃粦瀹氬埌涓涓鏈鍦板湴鍧鍜岀鍙d笂錛坆ind錛
4. 絳夊緟鎺ユ敹鏁版嵁錛坮ecvfrom錛
5. 鍏抽棴濂楁帴瀛(closesocket)
瀹㈡埛絝錛堝彂閫佺錛夌▼搴
1. 鍔犺澆濂楁帴瀛楀簱
2. 鍒涘緩濂楁帴瀛楋紙socket錛
3. 鍚戞湇鍔″櫒鍙戦佹暟鎹錛坰endto錛
4. 鍏抽棴濂楁帴瀛(closesocket)

Ⅲ UDP和Socket通信步驟

這是在網上找到的,希望對你有所幫助。
sockets(套接字)編程有三種,流式套接字(SOCK_STREAM),數據報套接字(SOCK_DGRAM),原始套接字(SOCK_RAW);

WINDOWS環境下TCP/UDP編程步驟:

1. 基於TCP的socket編程是採用的流式套接字。

在這個程序中,將兩個工程添加到一個工作區。要鏈接一個ws2_32.lib的庫文件。

伺服器端編程的步驟:

1:載入套接字型檔,創建套接字(WSAStartup()/socket());

2:綁定套接字到一個IP地址和一個埠上(bind());

3:將套接字設置為監聽模式等待連接請求(listen());

4:請求到來後,接受連接請求,返回一個新的對應於此次連接的套接字(accept());

5:用返回的套接字和客戶端進行通信(send()/recv());

6:返回,等待另一連接請求;

7:關閉套接字,關閉載入的套接字型檔(closesocket()/WSACleanup())。

伺服器端代碼如下:

#include <stdio.h>

#include <Winsock2.h>

void main()

{

WORD wVersionRequested;

WSADATA wsaData;

int err;

wVersionRequested = MAKEWORD( 1, 1 );

err = WSAStartup( wVersionRequested, &wsaData );

if ( err != 0 ) {

return;

}

if ( LOBYTE( wsaData.wVersion ) != 1 ||

HIBYTE( wsaData.wVersion ) != 1 ) {

WSACleanup( );

return;

}

SOCKET sockSrv=socket(AF_INET,SOCK_STREAM,0);

SOCKADDR_IN addrSrv;

addrSrv.sin_addr.S_un.S_addr=htonl(INADDR_ANY);

addrSrv.sin_family=AF_INET;

addrSrv.sin_port=htons(6000);

bind(sockSrv,(SOCKADDR*)&addrSrv,sizeof(SOCKADDR));

listen(sockSrv,5);

SOCKADDR_IN addrClient;

int len=sizeof(SOCKADDR);

while(1)

{

SOCKET sockConn=accept(sockSrv,(SOCKADDR*)&addrClient,&len);

char sendBuf[50];

sprintf(sendBuf,"Welcome %s to here!",inet_ntoa(addrClient.sin_addr));

send(sockConn,sendBuf,strlen(sendBuf)+1,0);

char recvBuf[50];

recv(sockConn,recvBuf,50,0);

printf("%s\n",recvBuf);

closesocket(sockConn);

}

}

客戶端編程的步驟:

1:載入套接字型檔,創建套接字(WSAStartup()/socket());

2:向伺服器發出連接請求(connect());

3:和伺服器端進行通信(send()/recv());

4:關閉套接字,關閉載入的套接字型檔(closesocket()/WSACleanup())。

客戶端的代碼如下:

#include <stdio.h>

#include <Winsock2.h>

void main()

{

WORD wVersionRequested;

WSADATA wsaData;

int err;

wVersionRequested = MAKEWORD( 1, 1 );

err = WSAStartup( wVersionRequested, &wsaData );

if ( err != 0 ) {

return;

}

if ( LOBYTE( wsaData.wVersion ) != 1 ||

HIBYTE( wsaData.wVersion ) != 1 ) {

WSACleanup( );

return;

}

SOCKET sockClient=socket(AF_INET,SOCK_STREAM,0);

SOCKADDR_IN addrSrv;

addrSrv.sin_addr.S_un.S_addr=inet_addr("127.0.0.1");

addrSrv.sin_family=AF_INET;

addrSrv.sin_port=htons(6000);

connect(sockClient,(SOCKADDR*)&addrSrv,sizeof(SOCKADDR));

char recvBuf[50];

recv(sockClient,recvBuf,50,0);

printf("%s\n",recvBuf);

send(sockClient,"hello",strlen("hello")+1,0);

closesocket(sockClient);

WSACleanup();

}

2.基於UDP的socket編程是採用的數據報套接字。

在這個程序中,將兩個工程添加到一個工作區。同時還要鏈接一個ws2_32.lib的庫文件。

伺服器端編程的步驟:

1:載入套接字型檔,創建套接字(WSAStartup()/socket());

2:綁定套接字到一個IP地址和一個埠上(bind());

3:等待和接收數據(sendto()/recvfrom());

4:關閉套接字,關閉載入的套接字型檔(closesocket()/WSACleanup())。

伺服器端代碼如下:

#include <winsock2.h>

#include <stdio.h>

void main()

{

WORD wVersionRequested;

WSADATA wsaData;

int err;

wVersionRequested = MAKEWORD( 1, 1 );

err = WSAStartup( wVersionRequested, &wsaData );

if ( err != 0 )

{

return;

}

if ( LOBYTE( wsaData.wVersion ) != 1 ||

HIBYTE( wsaData.wVersion ) != 1 )

{

WSACleanup( );

return;

}

SOCKET sockSrv=socket(AF_INET,SOCK_DGRAM,0);

SOCKADDR_IN addrSrv;

addrSrv.sin_addr.S_un.S_addr=htonl(INADDR_ANY);

addrSrv.sin_family=AF_INET;

addrSrv.sin_port=htons(7003);

bind(sockSrv,(SOCKADDR*)&addrSrv,sizeof(SOCKADDR));

char recvBuf[50];

SOCKADDR addrClient;

int len=sizeof(SOCKADDR);

recvfrom(sockSrv,recvBuf,50,0,(SOCKADDR*)&addrClient,&len);

printf("%s\n",recvBuf);

closesocket(sockSrv);

WSACleanup();

}

對於基於UDP的socket客戶端來說,要進行如下步驟:

1:創建一個套接字(socket);

2:向伺服器發送數據(sendto);

3:關閉套接字;

代碼如下:

#include <winsock2.h>

#include <stdio.h>

void main()

{

WORD wVersionRequested;

WSADATA wsaData;

int err;

wVersionRequested = MAKEWORD( 2, 2 );

err = WSAStartup( wVersionRequested, &wsaData );

if ( err != 0 ) {

return;

}

if ( LOBYTE( wsaData.wVersion ) != 2 ||

HIBYTE( wsaData.wVersion ) != 2 ) {

WSACleanup( );

return;

}

SOCKET sockClient=socket(AF_INET,SOCK_DGRAM,0);

SOCKADDR_IN addrClient;

addrClient.sin_addr.S_un.S_addr=inet_addr("127.0.0.1");

addrClient.sin_family=AF_INET;

addrClient.sin_port=htons(8889);

SOCKADDR_IN addrSrv;

sendto(sockClient,"hi",3,0,(SOCKADDR*)&addrClient,sizeof(SOCKADDR));

}

LINUX環境下TCP/UDP編程步驟:

TCP編程步驟:

一. 服務端:

1.socket(int domain,int type,int protocol):建立套接字;

2 .bind(int sockid,struct sockaddr *addrp,socklen_t addrlen):把本機地址和埠跟上一步建立的socket綁定在一起;

3.listen(int sockid,int qsize):監聽某套接字;

4.fd=accept(int sockid,struct sockaddr *callerid,socklen_t *addrlenp):等待某套接字接收信息;

5.recv(int fd,void *buf,size_t nbytes,int flags):從套接字接收數據;

6.close(fd) 和close(sockid)

二.客戶端:

1. socket():建立套接字;

2.connect(int sockid,struct sockaddr *serv_addrp,socklen_t addrlen):連接到伺服器;

3. send(int sockfd,const void *buf,size_t nbytes,int flags):發送數據到伺服器.

4. close(sockid);

UDP編程步驟:

一,服務端:

1. socket():同上;

2. bind():同上;

3. recvfrom(int sockfd,void*buff,size_t nbytes,int flags,struct sockaddr*from,socklen_t*addrlen):在套接字口接收數據,並且記錄下接收到的數據來源;一定要注意這里的參數addrlen,它不僅是函數的輸出,也是函數的輸入!所以要在調用該函數之前對addrlen賦值sizeof(struct sockaddr)。否則返回的地址from將會出錯!

4. close(sockfd);

二. 客戶端:

1. socket();同上;

2. sendto(int sockfd,const void*buff,size_t nbytes,int flags,const struct sockaddr*to,socklen_t addrlen):往指定的地址發送數據;

3. close(sockfd);

Ⅳ 在java中實現TCP協議編程中怎麼傳

在Java中實現TCP協議編程

ServerSocket:編寫TCP網路服務程序,首先要用到java.net.ServerSocket類用以創建伺服器Socket

構造方法:

ServerSocket(intport):創建綁定到特定埠的伺服器套接字

ServerSocket(intport,intbacklog):利用指定的backlog(伺服器忙時保持連接請求的等待客戶數量),創建伺服器套接字並將其綁定到指定的本地埠號。

ServerSocket(intport,intbacklog,InetAddressbindAddr):使用指定的埠、偵聽backlog和要綁定到的本地IP地址創建伺服器。

Socket:客戶端要與伺服器建立連接,必須先創建一個Socket對象

常用構造方法

Socket(Stringhost,intport):創建一個流套接字並將其連接到指定主機上的指定埠號。

Socket(InetAddressaddress,intport):創建一個流套接字並將其連接到指定IP地址的指定埠號。

伺服器端程序調用ServerSocket類中的accept()方法等待客戶端的連接請求,一旦accept()接收了客戶端連接請求,該方法返回一個與該客戶端建立了專線連接的Socket對象,不用程序去創建這個Socket對象。建立了連接的兩個Socket是以IO流的方式進行數據交換的,Java提供了Socket類中的getInputStream()返回Socket的輸入流對象,getOutputStream()返回Socket的輸出流對象。

TCP伺服器與TCP客戶端間的數據的接受圖示:

用TCP實現伺服器與客戶端的「聊天」:

實例代碼:

客戶端:

packagecom.hbsi.net;

importjava.net.Socket;

importjava.io.*;

publicclassTcpClient{

publicstaticvoidmain(String[]args)throwsException{

//1.建立tcp客戶端socket,要確定要連接的伺服器ip,port

Sockets=newSocket("192.168.49.87",9009);

//獲取鍵盤錄入

BufferedReaderbr=newBufferedReader(newInputStreamReader(System.in));

//2.通過建立的socket,獲取輸出流對象

//數據輸出給伺服器端

OutputStreamout=s.getOutputStream();

BufferedWriterbwout=newBufferedWriter(newOutputStreamWriter(out));

//獲取伺服器端返回的數據

//讀取伺服器端發過來的信息InputStreamReader()

BufferedReaderbrin=newBufferedReader(newInputStreamReader(

s.getInputStream()));

Stringline=null;

while((line=br.readLine())!=null){

if(line.equals("over"))

break;

bwout.write(line);

bwout.newLine();

bwout.flush();

Stringstr=brin.readLine();

System.out.println("server:"+str);

}

br.close();

s.close();

}

}

伺服器端:

packagecom.hbsi.net;

importjava.io.BufferedReader;

importjava.io.BufferedWriter;

importjava.io.InputStream;

importjava.io.InputStreamReader;

importjava.io.OutputStreamWriter;

importjava.net.ServerSocket;

importjava.net.Socket;

publicclassTcpServer{

publicstaticvoidmain(String[]args)throwsException{

//1.建立伺服器socket

ServerSocketss=newServerSocket(9009);

//2.調用accept()

Sockets=ss.accept();

System.out.println(s.getInetAddress().getHostAddress()

+"...connection");

//讀取客戶的信息的輸入流

InputStreamin=s.getInputStream();

BufferedReaderbrin=newBufferedReader(newInputStreamReader(in));

//向客戶端發送信息輸出流,服務端向客戶端返回信息OutputStreamWriter()

BufferedWriterbrout=newBufferedWriter(newOutputStreamWriter(

s.getOutputStream())); Stringline=null;

while((line=brin.readLine())!=null){

System.out.println("client:"+line);

brout.write(line.toUpperCase());//伺服器端收到信息後,將信息轉為大寫返回給客戶端toUpperCase()

brout.newLine();

brout.flush();

}

s.close();

ss.close();

}

}

Ⅳ C#中TCP進行同步套接字編程,伺服器和客戶端的工作流程(需要代碼和圖)

代碼來了,。。
伺服器:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;
using System.Reflection;
using System.Diagnostics;
using System.Text.RegularExpressions;

namespace msgServer
{
public partial class frmServer : Form
{
private Socket socket;
private IPAddress myIP;
private IPEndPoint endPoint;
private int point;
private Socket clientSocket;
private Assembly ass = null;
private System.IO.Stream stream = null;
private System.Media.SoundPlayer pl;
private string txt;
private byte[] bs = new byte[512];
public frmServer()
{
InitializeComponent();
ass = Assembly.GetExecutingAssembly();
stream = ass.GetManifestResourceStream("msgServer.msg.wav");
pl = new System.Media.SoundPlayer(stream);
}

//字體選擇
private void btnFont_Click(object sender, EventArgs e)
{
FontDialog font = new FontDialog();
font.ShowEffects = true;
font.ShowColor = true;
font.MinSize = 12;
font.Font = new Font("楷體_GB2312", 18, FontStyle.Bold);
font.Color = Color.Blue;

if (font.ShowDialog() == DialogResult.OK)
{
rtxtSend.Font = font.Font;
rtxtSend.ForeColor = font.Color;
}

}

//開始監聽
private void btnStart_Click(object sender, EventArgs e)
{
System.Threading.Thread th1 = new System.Threading.Thread(ToConnect);
th1.Start();
}

//去連接
private void ToConnect()
{
try
{
myIP = IPAddress.Parse(txtIP.Text.Trim());//IP
point = Convert.ToInt32(txtPoint.Text.Trim());//Point
endPoint = new IPEndPoint(myIP, point); //終端

socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Bind(endPoint);//綁定
socket.Listen(3); //最多3人同時連接

lblStatus.Text = "伺服器已經運行...";

clientSocket = socket.Accept();//等待接受
//連接上時
if (clientSocket.Connected)
{
lblStatus.Text = "已經建立連接.";

while (true)
{
try
{
clientSocket.Receive(bs, bs.Length, 0);
pl.Play();
rtxtMsg.AppendText(System.Text.Encoding.Unicode.GetString(bs));
}
catch { lblStatus.Text = "連接已經斷開."; }
}
}
}
catch { txtIP.Focus(); txtIP.SelectAll(); MessageBox.Show("IP error OR Point error"); }
}

//停止監聽
private void btnStop_Click(object sender, EventArgs e)
{
try
{
socket.Close(3);
lblStatus.Text = "監聽已經停止.";
}
catch
{
lblStatus.Text = "目前未建立連接.";
}
}

private void frmServer_KeyPress(object sender, KeyPressEventArgs e)
{

}

private void frmServer_KeyDown(object sender, KeyEventArgs e)
{
if ((e.Control && e.KeyCode == Keys.Enter) || (e.Alt && e.KeyCode == Keys.S))
{
btnSend.PerformClick();//單擊發送
}
}

//發送消息
private void btnSend_Click(object sender, EventArgs e)
{
if (rtxtSend.Text.Trim() == "")
return;
else if (rtxtSend.Text.Trim().ToLower() == "clear()")
{
rtxtMsg.Clear();
rtxtSend.Text = "";
return;
}
else if (Regex.IsMatch(rtxtSend.Text.Trim().ToLower(), @"^[zoom(]+[\d]+[)]$"))
{
string str = rtxtSend.Text.ToLower();
int size = Convert.ToInt32(str.Substring(str.LastIndexOf('(') + 1,
str.IndexOf(')') - str.LastIndexOf('(') - 1));
rtxtMsg.Font = new Font("宋體", size,FontStyle.Bold);
return;
}
else if (Regex.IsMatch(rtxtSend.Text.Trim().ToLower(), @"^[down(]+[\d]+[)]$"))
{
string str = rtxtSend.Text.ToLower();
string size = str.Substring(str.LastIndexOf('(') + 1,str.IndexOf(')') - str.LastIndexOf('(') - 1);

if (Convert.ToInt32(size) > rtxtMsg.Text.Length)
return;

}
else if (Regex.IsMatch(rtxtSend.Text.Trim().ToLower(), @"^[up(]+[\d]+[)]$"))
{
string str = rtxtSend.Text.ToLower();
string size = str.Substring(str.LastIndexOf('(') + 1,str.IndexOf(')') - str.LastIndexOf('(') - 1);

}
else if (rtxtSend.Text.Trim().ToLower() == "exit(0)")
{
this.Close();
return;
}

try
{
byte[] bs = new byte[512];
string user = null;
if (txtUser.Text.Trim() == "在此輸入你的名字" || txtUser.Text.Trim() == "")
{
user = "我";
bs = Encoding.Unicode.GetBytes(string.Format("對方說:({0})\r\n{1}\r\n",DateTime.Now.ToString(), rtxtSend.Text.Trim()));
}
else
{
bs = Encoding.Unicode.GetBytes(string.Format("{0}說:({1})\r\n{2}\r\n", txtUser.Text.Trim(),DateTime.Now.ToString(), rtxtSend.Text.Trim()));
user = txtUser.Text.Trim();
}
clientSocket.Send(bs, bs.Length, 0);//發送
txt = string.Format("{0}說:({1})\r\n{2}\r\n", user, DateTime.Now.ToString(),rtxtSend.Text.Trim());
int tempLen = rtxtMsg.Text.Length;
rtxtMsg.AppendText(txt);
rtxtMsg.Select(tempLen, txt.Length);
rtxtMsg.SelectionFont = new Font("宋體", 10);
rtxtMsg.SelectionColor = Color.Red;
rtxtSend.Clear();
}
catch { MessageBox.Show("未建立連接,無法發送數據!"); }
}

//關閉Socket
private void frmServer_FormClosing(object sender, FormClosingEventArgs e)
{
try
{
//關閉連接
socket.Close(3);
}
catch (Exception) { }
finally
{
foreach (Process p in Process.GetProcesses())
{
if (p.ProcessName == Application.ProctName)
p.Kill();
}
}
}

private void frmServer_Load(object sender, EventArgs e)
{
foreach (Process p in Process.GetProcesses())
{
if (p.ProcessName == Application.ProctName)//已經啟動
{
if (p.Id != Process.GetCurrentProcess().Id)//不是當前進程
{
p.Kill();
}
}
}
}

private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
this.TopMost = checkBox1.Checked;
}
}
}

客戶端:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Diagnostics;
using System.Text.RegularExpressions;

namespace smgClient
{
public partial class frmClient : Form
{
private IPAddress IP;//ip
private EndPoint endpoint;//point
private Socket socket;//socket
private System.IO.Stream stream = null;
private System.Reflection.Assembly ass = null;
private System.Media.SoundPlayer pl = null;
private string txt;
private byte[] bs = new byte[512];

public frmClient()
{
InitializeComponent();
ass = System.Reflection.Assembly.GetExecutingAssembly();
stream = ass.GetManifestResourceStream("smgClient.msg.wav");
pl = new System.Media.SoundPlayer(stream);
}

//請求連接
private void btnRequestConnect_Click(object sender, EventArgs e)
{
System.Threading.Thread th = new System.Threading.Thread(this.ToConnect);
th.Start();
}

//連接伺服器
private void ToConnect()
{
try
{
IP = IPAddress.Parse(txtIP.Text.Trim());
int point = Convert.ToInt32(txtPoint.Text.Trim());
endpoint = new IPEndPoint(IP, point);
//建立Socket
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//建立連接
socket.Connect(endpoint);
//連接成功
lblStatus.Text = "連接成功.";

while (true)
{
socket.Receive(bs, bs.Length, 0);
pl.Play();
rtxtMsg.AppendText(System.Text.Encoding.Unicode.GetString(bs));
}
}
catch (FormatException)
{ MessageBox.Show("IP error OR Point error"); }
catch (ArgumentNullException)
{ MessageBox.Show("IP error OR Point error"); }
catch (Exception)
{
lblStatus.Text = "連接失敗,原因: 伺服器已停止.";
}
}

//字體
private void btnFont_Click(object sender, EventArgs e)
{
FontDialog font = new FontDialog();
font.ShowEffects = true;
font.ShowColor = true;
font.MinSize = 12;
font.Font = new Font("楷體_GB2312", 18, FontStyle.Bold);
font.Color = Color.Blue;

if (font.ShowDialog() == DialogResult.OK)
{
rtxtSend.Font = font.Font;
rtxtSend.ForeColor = font.Color;
}
}

//關閉連接
private void btnCloseConnect_Click(object sender, EventArgs e)
{
try
{
socket.Close();
lblStatus.Text = "連接已經關閉.";
}
catch
{
lblStatus.Text = "目前未建立連接.";
}
}

//發送消息
private void btnSend_Click(object sender, EventArgs e)
{
if (rtxtSend.Text.Trim() == "")
return;
else if (rtxtSend.Text.Trim().ToLower() == "clear()")
{
rtxtMsg.Clear();
rtxtSend.Text = "";
return;
}
else if (Regex.IsMatch(rtxtSend.Text.Trim().ToLower(), @"^[zoom(]+[\d]+[)]$"))
{
string str = rtxtSend.Text.ToLower();
int size = Convert.ToInt32(str.Substring(str.LastIndexOf('(') + 1,
str.IndexOf(')') - str.LastIndexOf('(') - 1));
rtxtMsg.Font = new Font("宋體", size, FontStyle.Bold);
return;
}
else if (Regex.IsMatch(rtxtSend.Text.Trim().ToLower(), @"^[down(]+[\d]+[)]$"))
{
string str = rtxtSend.Text.ToLower();
string size = str.Substring(str.LastIndexOf('(') + 1, str.IndexOf(')') - str.LastIndexOf('(') - 1);

if (Convert.ToInt32(size) > rtxtMsg.Text.Length)
return;

}
else if (Regex.IsMatch(rtxtSend.Text.Trim().ToLower(), @"^[up(]+[\d]+[)]$"))
{
string str = rtxtSend.Text.ToLower();
string size = str.Substring(str.LastIndexOf('(') + 1, str.IndexOf(')') - str.LastIndexOf('(') - 1);

}
else if (rtxtSend.Text.Trim().ToLower() == "exit(0)")
{
this.Close();
return;
}

try
{
byte[] bs = new byte[512];
string user = null;
if (txtUser.Text.Trim() == "在此輸入你的名字" || txtUser.Text.Trim() == "")
{
user = "我";
bs = Encoding.Unicode.GetBytes(string.Format("對方說:({0})\r\n{1}\r\n", DateTime.Now.ToString(),rtxtSend.Text.Trim()));
}
else
{
bs = Encoding.Unicode.GetBytes(string.Format("{0}說:({1})\r\n{2}\r\n", txtUser.Text.Trim(),DateTime.Now.ToString(),rtxtSend.Text.Trim()));
user = txtUser.Text.Trim();
}

socket.Send(bs, bs.Length, 0);//發送

txt = string.Format("{0}說:({1})\r\n{2}\r\n", user, DateTime.Now.ToString(), rtxtSend.Text.Trim());
int tempLen = rtxtMsg.Text.Length;
rtxtMsg.AppendText(txt);
rtxtMsg.Select(tempLen, txt.Length);
rtxtMsg.SelectionFont = new Font("宋體", 10);
rtxtMsg.SelectionColor = Color.Red;
rtxtSend.Clear();
}
catch(Exception ex)
{ MessageBox.Show("連接尚未建立!無法發送數據!" + ex.Message); }
}

//避開打開多個
private void frmClient_Load(object sender, EventArgs e)
{
foreach (Process p in Process.GetProcesses())
{
if (p.ProcessName == Application.ProctName)//有進程
{
if (p.Id != Process.GetCurrentProcess().Id)//不是當前進程
{
p.Kill();
}
}
}
}

private void frmClient_FormClosing(object sender, FormClosingEventArgs e)
{
try
{
socket.Close();
}
catch(Exception) { }
finally
{
foreach (Process p in Process.GetProcesses())
{
if (p.ProcessName == Application.ProctName)
p.Kill();
}
}
}

private void frmClient_KeyDown(object sender, KeyEventArgs e)
{
if ((e.Control && e.KeyCode == Keys.Enter) || (e.Alt && e.KeyCode == Keys.S))
{
btnSend.PerformClick();
}
}

private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
this.TopMost = checkBox1.Checked;
}
}
}

Ⅵ C++ 如何使用 Socket 類向 HTTP 伺服器發送數據和接收響應

客戶端發送請求給伺服器,伺服器處理完畢以後把Socket tempSocket = (你還可以檢測收到的1W8數據是3W8裡面的哪一部分. 這個把發送的數據和接收的

閱讀全文

與套接字客戶端如何連接到伺服器相關的資料

熱點內容
android兼容測試工具 瀏覽:96
雲伺服器不支持虛擬化怎麼辦 瀏覽:189
加密方式的演變 瀏覽:364
java常用演算法pdf 瀏覽:734
伺服器數據遇到異常什麼原因 瀏覽:450
phpexif信息 瀏覽:542
單片機三位元組浮點數 瀏覽:756
命令與征服泰伯利亞戰爭下載 瀏覽:378
c窗口界面編程 瀏覽:23
hypermill編程能做模板嗎 瀏覽:782
計算機網路最經典的演算法 瀏覽:628
華為思科的配置命令 瀏覽:869
linux設置光碟啟動 瀏覽:361
程序員俱樂部注冊 瀏覽:19
洗潔精雞蛋盤解壓視頻 瀏覽:294
企業內網加密app 瀏覽:51
騰訊雲伺服器怎麼設置本地網路 瀏覽:625
日常程序員 瀏覽:515
哪個pe有bit加密功能 瀏覽:111
rust伺服器是用什麼ip 瀏覽:694