導航:首頁 > 源碼編譯 > socket源碼

socket源碼

發布時間:2022-02-10 04:22:05

㈠ 求C++,socket聊天程序的代碼,最好是實現了兩個客戶端之間經由伺服器的信息互發,聊天功能要完整些

#include <stdio.h>
#include <winsock2.h>
#define MAX_SIZE 200
void main(void) {
WORD wVersionRequested;
WSADATA wsaData;
int err;

wVersionRequested = MAKEWORD( 1, 1 );

err = WSAStartup( wVersionRequested, &wsaData );
if ( err != 0 ) {
/* Tell the user that we could not find a usable */
/* WinSock DLL. */
return;
}
/* Confirm that the WinSock DLL supports 2.2.*/
/* Note that if the DLL supports versions greater */
/* than 2.2 in addition to 2.2, it will still return */
/* 2.2 in wVersion since that is the version we */
/* requested. */
if ( LOBYTE( wsaData.wVersion ) != 1 ||
HIBYTE( wsaData.wVersion ) != 1 ) {
/* Tell the user that we could not find a usable */
/* WinSock DLL. */
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(6000);
bind(sockSrv, (SOCKADDR *)&addrSrv, sizeof(SOCKADDR));
SOCKADDR addrClient;
char recvBuffer[MAX_SIZE];
memset(recvBuffer, 0, sizeof(recvBuffer));
int len = sizeof(SOCKADDR);
recvfrom(sockSrv, recvBuffer, sizeof(recvBuffer), 0, (SOCKADDR *)&addrClient, &len);

printf("%s\n", recvBuffer);
closesocket(sockSrv);
}
#include <stdio.h>
#include <winsock2.h>
void main(void) {
WORD wVersionRequested;
WSADATA wsaData;
int err;

wVersionRequested = MAKEWORD( 1, 1 );

err = WSAStartup( wVersionRequested, &wsaData );
if ( err != 0 ) {
/* Tell the user that we could not find a usable */
/* WinSock DLL. */
return;
}

/* Confirm that the WinSock DLL supports 2.2.*/
/* Note that if the DLL supports versions greater */
/* than 2.2 in addition to 2.2, it will still return */
/* 2.2 in wVersion since that is the version we */
/* requested. */

if ( LOBYTE( wsaData.wVersion ) != 1 ||
HIBYTE( wsaData.wVersion ) != 1 ) {
/* Tell the user that we could not find a usable */
/* WinSock DLL. */
WSACleanup( );
return;
}

/* The WinSock DLL is acceptable. Proceed. */

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(6000);
sendto(sockClient, "你若此生若只如一瞬", strlen("你若此生若只如一瞬"), 0, (SOCKADDR *)&addrClient, sizeof(SOCKADDR));
closesocket(sockClient);
WSACleanup();
}

㈡ 這段socket代碼的注釋 誰給加點詳細注釋啊 謝謝

要分好幾次發送,第一次還沒發完就回調了,在回調函數中再來第二次發送不就出異常了)。
2.數據接收完畢或者緩沖區滿了時。(如果沒有數據發過來,這個線程會一直掛起,沒有「超過某個時間就回調」的說法)。
3.數據發送完畢和關閉Socket有什麼聯系呢,數據發送完了,Socket連接還在呀, 除非你調用了Socket.ShutDown(SocketShutdown.Both)時就不能收發數據了,Socket.Close()才會關閉Socket,Socket的關閉是由你來控制的。

例子:(隨便寫了幾句代碼,給你加點注釋)

int i;
int size = 1024;
byte buffer = new byte[size];
//讀文件
FileStream fs =new FileStream(filename,FileMode.Open,FileAccess.Read);
//將文件轉化成二進制流(不然怎麼傳)
BinaryReader br = new BinaryReader(fs);
Socket sock = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
//連接對方主機的ip地址和偵聽埠
sock.Connect(ip, port);
//將文件的二進制流讀入緩沖區
br.Read(buffer, 0, size);
//將緩沖區的內容非同步發送出去,委託回調函數EndSendFile()在後面
sock.BeginSend(buffer, 0, size, SocketFlags.None,
new AsyncCallback(EndSendFile), null);

private void EndSendFile(IAsyncResult AR)
{
//結束掛起的非同步發送
sock.EndSend(AR);
//判斷文件是否讀完,沒讀完繼續讀到緩沖區
if ((i = br.Read(buffer, 0, size)) != 0)
{
//發送緩沖區內容,你看清楚回調函數(就是本函數)
//就是說這次發送完後又調用這個函數來判斷和發送
sock.BeginSend(buffer, 0, size, SocketFlags.None,
new AsyncCallback(EndSendFile), null);
}
}

這是我隨便寫的幾句代碼,不過我以前都實踐過的,應該是對的,你想運行它的話,還要自己加點東西,還要寫個接收程序(非同步接收的話就用你說的BeginReceive()試一試)。
另外,團IDC網上有許多產品團購,便宜有口碑

㈢ 求實現基於java Socket網路通信的客戶端和伺服器端的源代碼。

伺服器端Server.java: import java.io.*;import java.net.*; public class Server{ publicstatic void main(String[] args) { try{ ServerSocket s = newServerSocket(9000); while (true) { Socket incoming =s.accept(); try { FileInputStreamfstream = new FileInputStream("Server.java"); //假設輸入文件為Server.java DataInputStream in =new DataInputStream(fstream); BufferedReaderbr = new BufferedReader(new InputStreamReader(in)); OutputStreamostream = incoming.getOutputStream(); PrintWriterout = new PrintWriter(ostream, true); String strLine; while ((strLine =br.readLine()) != null) { out.println(strLine); } in.close(); } finally { incoming.close(); } } }catch (Exception e){ e.printStackTrace(); } }} 客戶端Client.java: import java.io.*;import java.net.*;import java.util.*; public class Client{ publicstatic void main(String[] args) { try { Sockets = new Socket("localhost", 9000); try { InputStreaminStream = s.getInputStream(); Scannerin = new Scanner(inStream); PrintWriter out = newPrintWriter("test.txt");//假設輸出文件為test.txt while(in.hasNextLine()) { Stringline = in.nextLine(); System.out.println(line); out.println(line); } out.close(); } finally { s.close(); } } catch(IOException e) { e.printStackTrace(); } }}

㈣ 如何安裝luasocket源碼

第一種方法:如果你有安裝了 Lua 模塊的安裝和部署工具 LuaRocks,那麼一條指令就能安裝部署好 LuaSocket:
# luarocks install luasocket
第二種方法:如果沒安裝有 LuaRocks,也可以源碼安裝。
先把 LuaRocks 下載下來,當前可用的版本是 luasocket-3.0-rc1(luasocket的源碼有託管在Github.com):
# git clone https://github.com/diegonehab/luasocket.git
把源碼clone下來之後就可以進行本地源碼安裝,直接進入到luasocket目錄進行編譯安裝了
# cd luasocket
# make && make install

㈤ 求一個socket聊天程序源碼 C語言的

通過socket編程自己寫一個唄,可以學習一下socket編程方面的知識

㈥ 如何運行socket 代碼

呵呵 這個工具剛剛用過 SocketTool
這個是windows下面的,可以裝在windows下面,分別測試你linux的客戶端和服務端
有郵箱的話 我發給你

㈦ 如何看javawebsocket源碼

import java.io.IOException;
import java.io.InputStream;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

@ServerEndpoint("/log")
public class LogWebSocketHandle {

private Process process;
private InputStream inputStream;

/**
* 新的WebSocket請求開啟
*/
@OnOpen
public void onOpen(Session session) {
try {
// 執行tail -f命令
process = Runtime.getRuntime().exec("tail -f /var/log/syslog");
inputStream = process.getInputStream();

// 一定要啟動新的線程,防止InputStream阻塞處理WebSocket的線程
TailLogThread thread = new TailLogThread(inputStream, session);
thread.start();
} catch (IOException e) {
e.printStackTrace();
}
}

/**
* WebSocket請求關閉
*/
@OnClose
public void onClose() {
try {
if(inputStream != null)
inputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
if(process != null)
process.destroy();
}

@OnError
public void onError(Throwable thr) {
thr.printStackTrace();
}
}

㈧ socket編程問題(附代碼)

1.首先你的程序時是單線程的程序。
2.基於SOCKET的程序,也就是C/S程序,要區分那個是C,那個是S。
3.建議你看下孫鑫的VC++視頻裡面的基於SOCKET通信。

php100 socket類源碼

email.class.php <?php class smtp { /* Public Variables */ var $smtp_port; var $time_out; var $host_name; var $log_file; var $relay_host; var $debug; var $auth; var $user; var $pass; /* Private Variables */ var $sock; /* Constractor */ function smtp($relay_host = "", $smtp_port = 25,$auth = false,$user,$pass) { $this->debug = FALSE; $this->smtp_port = $smtp_port; $this->relay_host = $relay_host; $this->time_out = 30; //is used in fsockopen() # $this->auth = $auth;//auth $this->user = $user; $this->pass = $pass; # $this->host_name = "localhost"; //is used in HELO command $this->log_file =""; $this->sock = FALSE; } /* Main Function */ function sendmail($to, $from, $subject = "", $body = "", $mailtype, $cc = "", $bcc = "", $additional_headers = "") { $mail_from = $this->get_address($this->strip_comment($from)); $body = ereg_replace("(^|(\r\n))(\\.)", "\\1.\\3", $body); $header .= "MIME-Version:1.0\r\n"; if($mailtype=="HTML"){ $header .= "Content-Type:text/html\r\n"; } $header .= "To: ".$to."\r\n"; if ($cc != "") { $header .= "Cc: ".$cc."\r\n"; } $header .= "From: $from<".$from.">\r\n"; $header .= "Subject: ".$subject."\r\n"; $header .= $additional_headers; $header .= "Date: ".date("r")."\r\n"; $header .= "X-Mailer:By Redhat (PHP/".phpversion().")\r\n"; list($msec, $sec) = explode(" ", microtime()); $header .= "Message-ID: <".date("YmdHis", $sec).".".($msec*1000000).".".$mail_from.">\r\n"; $TO = explode(",", $this->strip_comment($to)); if ($cc != "") { $TO = array_merge($TO, explode(",", $this->strip_comment($cc))); } if ($bcc != "") { $TO = array_merge($TO, explode(",", $this->strip_comment($bcc))); } $sent = TRUE; foreach ($TO as $rcpt_to) { $rcpt_to = $this->get_address($rcpt_to); if (!$this->smtp_sockopen($rcpt_to)) { $this->log_write("Error: Cannot send email to ".$rcpt_to."\n"); $sent = FALSE; continue; } if ($this->smtp_send($this->host_name, $mail_from, $rcpt_to, $header, $body)) { $this->log_write("E-mail has been sent to <".$rcpt_to.">\n"); } else { $this->log_write("Error: Cannot send email to <".$rcpt_to.">\n"); $sent = FALSE; } fclose($this->sock); $this->log_write("Disconnected from remote host\n"); } echo "<br>"; echo $header; return $sent; } /* Private Functions */ function smtp_send($helo, $from, $to, $header, $body = "") { if (!$this->smtp_putcmd("HELO", $helo)) { return $this->smtp_error("sending HELO command"); } #auth if($this->auth){ if (!$this->smtp_putcmd("AUTH LOGIN", base64_encode($this->user))) { return $this->smtp_error("sending HELO command"); } if (!$this->smtp_putcmd("", base64_encode($this->pass))) { return $this->smtp_error("sending HELO command"); } } # if (!$this->smtp_putcmd("MAIL", "FROM:<".$from.">")) { return $this->smtp_error("sending MAIL FROM command"); } if (!$this->smtp_putcmd("RCPT", "TO:<".$to.">")) { return $this->smtp_error("sending RCPT TO command"); } if (!$this->smtp_putcmd("DATA")) { return $this->smtp_error("sending DATA command"); } if (!$this->smtp_message($header, $body)) { return $this->smtp_error("sending message"); } if (!$this->smtp_eom()) { return $this->smtp_error("sending <CR><LF>.<CR><LF> [EOM]"); } if (!$this->smtp_putcmd("QUIT")) { return $this->smtp_error("sending QUIT command"); } return TRUE; } function smtp_sockopen($address) { if ($this->relay_host == "") { return $this->smtp_sockopen_mx($address); } else { return $this->smtp_sockopen_relay(); } } function smtp_sockopen_relay() { $this->log_write("Trying to ".$this->relay_host.":".$this->smtp_port."\n"); $this->sock = @fsockopen($this->relay_host, $this->smtp_port, $errno, $errstr, $this->time_out); if (!($this->sock && $this->smtp_ok())) { $this->log_write("Error: Cannot connenct to relay host ".$this->relay_host."\n"); $this->log_write("Error: ".$errstr." (".$errno.")\n"); return FALSE; } $this->log_write("Connected to relay host ".$this->relay_host."\n"); return TRUE;; } function smtp_sockopen_mx($address) { $domain = ereg_replace("^.+@([^@]+)$", "\\1", $address); if (!@getmxrr($domain, $MXHOSTS)) { $this->log_write("Error: Cannot resolve MX \"".$domain."\"\n"); return FALSE; } foreach ($MXHOSTS as $host) { $this->log_write("Trying to ".$host.":".$this->smtp_port."\n"); $this->sock = @fsockopen($host, $this->smtp_port, $errno, $errstr, $this->time_out); if (!($this->sock && $this->smtp_ok())) { $this->log_write("Warning: Cannot connect to mx host ".$host."\n"); $this->log_write("Error: ".$errstr." (".$errno.")\n"); continue; } $this->log_write("Connected to mx host ".$host."\n"); return TRUE; } $this->log_write("Error: Cannot connect to any mx hosts (".implode(", ", $MXHOSTS).")\n"); return FALSE; } function smtp_message($header, $body) { fputs($this->sock, $header."\r\n".$body); $this->smtp_debug("> ".str_replace("\r\n", "\n"."> ", $header."\n> ".$body."\n> ")); return TRUE; } function smtp_eom() { fputs($this->sock, "\r\n.\r\n"); $this->smtp_debug(". [EOM]\n"); return $this->smtp_ok(); } function smtp_ok() { $response = str_replace("\r\n", "", fgets($this->sock, 512)); $this->smtp_debug($response."\n"); if (!ereg("^[23]", $response)) { fputs($this->sock, "QUIT\r\n"); fgets($this->sock, 512); $this->log_write("Error: Remote host returned \"".$response."\"\n"); return FALSE; } return TRUE; } function smtp_putcmd($cmd, $arg = "") { if ($arg != "") { if($cmd=="") $cmd = $arg; else $cmd = $cmd." ".$arg; } fputs($this->sock, $cmd."\r\n"); $this->smtp_debug("> ".$cmd."\n"); return $this->smtp_ok(); } function smtp_error($string) { $this->log_write("Error: Error occurred while ".$string.".\n"); return FALSE; } function log_write($message) { $this->smtp_debug($message); if ($this->log_file == "") { return TRUE; } $message = date("M d H:i:s ").get_current_user()."[".getmypid()."]: ".$message; if (!@file_exists($this->log_file) || !($fp = @fopen($this->log_file, "a"))) { $this->smtp_debug("Warning: Cannot open log file \"".$this->log_file."\"\n"); return FALSE; } flock($fp, LOCK_EX); fputs($fp, $message); fclose($fp); return TRUE; } function strip_comment($address) { $comment = "\\([^()]*\\)"; while (ereg($comment, $address)) { $address = ereg_replace($comment, "", $address); } return $address; } function get_address($address) { $address = ereg_replace("([ \t\r\n])+", "", $address); $address = ereg_replace("^.*<(.+)>.*$", "\\1", $address); return $address; } function smtp_debug($message) { if ($this->debug) { echo $message."<br>"; } } function get_attach_type($image_tag) { // $filedata = array(); $img_file_con=fopen($image_tag,"r"); unset($image_data); while ($tem_buffer=AddSlashes(fread($img_file_con,filesize($image_tag)))) $image_data.=$tem_buffer; fclose($img_file_con); $filedata['context'] = $image_data; $filedata['filename']= basename($image_tag); $extension=substr($image_tag,strrpos($image_tag,"."),strlen($image_tag)-strrpos($image_tag,".")); switch($extension){ case ".gif": $filedata['type'] = "image/gif"; break; case ".gz": $filedata['type'] = "application/x-gzip"; break; case ".htm": $filedata['type'] = "text/html"; break; case ".html": $filedata['type'] = "text/html"; break; case ".jpg": $filedata['type'] = "image/jpeg"; break; case ".tar": $filedata['type'] = "application/x-tar"; break; case ".txt": $filedata['type'] = "text/plain"; break; case ".zip": $filedata['type'] = "application/zip"; break; default: $filedata['type'] = "application/octet-stream"; break; } return $filedata; } } ?> ----------------------------------------- sendmail.php <?php require_once ('email.class.php'); //########################################## $smtpserver = "smtp.163.com";//SMTP伺服器 $smtpserverport =25;//SMTP伺服器埠 $smtpusermail = "";//SMTP伺服器的用戶郵箱 $smtpemailto = "";//發送給誰 $smtpuser = "";//SMTP伺服器的用戶帳號 $smtppass = "";//SMTP伺服器的用戶密碼 $mailsubject = "PHP100測試郵件系統";//郵件主題 $mailbody = "<h1> 這是一個測試程序 PHP100.com </h1>";//郵件內容 $mailtype = "HTML";//郵件格式(HTML/TXT),TXT為文本郵件 ########################################## $smtp = new smtp($smtpserver,$smtpserverport,true,$smtpuser,$smtppass);//這裡面的一個true是表示使用身份驗證,否則不使用身份驗證. $smtp->debug = FALSE;//是否顯示發送的調試信息 $smtp->sendmail($smtpemailto, $smtpusermail, $mailsubject, $mailbody, $mailtype); ?>

㈩ 在那裡可以看到socket()函數的源代碼

這是微軟的機密,沒有向我們提供,只提供了頭文件。

還有你的基礎不好,要努力啊。
include只會包含頭文件,一般是.h

如果你要看類似的代碼,可以去www.freebsd.org.cn的伺服器下載freeBSD的源代碼慢慢看。(socket是誰發明的,我想你知道吧。)

建設性的建議:看看
<<TCP/IP詳解,卷1:協議>>
<<TCP/IP詳解,卷2:實現>>
<<TCP/IP詳解,卷3:TCP事務協議 HTTP NNTP和UNIX域協議>>

沒有比這更好的書了,可惜作者死得早。

閱讀全文

與socket源碼相關的資料

熱點內容
新軒逸經典如何安裝安卓應用 瀏覽:18
php大流量網站 瀏覽:149
買車app哪個是正規的 瀏覽:171
python中的class是什麼 瀏覽:202
安卓導航屏如何接燈光線 瀏覽:691
哪個app能查天津違章 瀏覽:431
預訂汽車票在哪個app 瀏覽:704
五菱宏光壓縮機安裝 瀏覽:460
蘋果電腦怎麼編譯vlc 瀏覽:107
多感測數據融合演算法 瀏覽:213
access2010壓縮 瀏覽:152
安卓最舊系統是什麼 瀏覽:709
草根到百萬程序員 瀏覽:699
學員招聘app哪個好 瀏覽:451
感到解壓就拍拍手 瀏覽:113
php404頁面代碼 瀏覽:719
php唯一編號 瀏覽:601
硬碟文件夾沒法打開 瀏覽:445
訪問外網的svn伺服器地址 瀏覽:880
想去自由行有什麼好的app 瀏覽:215