导航:首页 > 源码编译 > 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源码相关的资料

热点内容
php如何放到服务器里 浏览:245
红色警戒2安装加密密码 浏览:150
php集群session 浏览:767
sct报价存储服务器怎么选 浏览:725
金蝶硬加密怎么样 浏览:385
linux桌面虚拟化 浏览:90
时间动态加密怎么解密 浏览:281
美女玩声控解压 浏览:367
编程人员组装电脑 浏览:463
燕窝新版溯源码 浏览:77
程序员吃青春饭的好处 浏览:663
浙江戴尔服务器云空间 浏览:330
网站锁源码 浏览:823
CAd打印文件命令 浏览:501
小米5sp无法复制加密门禁 浏览:831
文件夹添加密码怎么找回 浏览:800
安卓怎么校色 浏览:279
android基本框架 浏览:851
解压包子小了怎么补救 浏览:989
有什么管理客户的app 浏览:708