1、用c語言socket編程伺服器和客戶端能相互傳文件,請問怎樣在伺服器端設置帳號和密碼,在下載時能顯示進度條
1、可以在client端登入時抄write(發送)帳號和密碼給server端,當server端接受到內容時判斷是否是你預設的帳號密碼,是則允許下載,否則關閉其socket。
2、是要客戶端看到進度條? 這樣就要要求在下載文件時server端要先發這個文件的大小給client端,client端就可以通過這個大小和接受到的位元組數比較後列印進度條(printf("#");).
文件大小可用int stat(const char *restrict path, struct stat *restrict buf);函數獲取。
2、VC csocket伺服器端代碼和客戶端代碼在一台電腦上正常,在兩台電腦上有故障
同意魔高丈,應該是線程同步的問題。
解碼線程是不是和接收線程採用同一個緩沖區?
如果是,那前者讀,後者寫,你應該有一個機制保證讀的時候,不允許後者寫,否則接收線程會覆蓋緩沖區數據,讓解碼線程讀不到正確的數據。
可以用臨界條件CriticalSection,鎖之類,信號量之類的實現保證數據一致性。
3、C用一個socket實現一個伺服器接收兩個客戶端的信息並保存
服務端監聽socket正常是不與任何客戶端socket進行通信的。監聽socket死循環作監聽工作,當收到一個連接之後,創建一個新的socket來與客戶端通信。這樣理論上一個服務端可以與上萬的客戶端通信。只是要記住,每個真正參與通信的socket都需要開兩個單獨的線程來進行消息的收發。
4、C語言Socket伺服器怎麼給客戶端發消息
你的文件中的問題
// 會阻塞進程,直到有客戶端連接上來為止
// 既然是直到有客戶端連接上,那麼就要弄明白哪個是與客戶端連接的套接字
// sockClient就是與客戶端連接的套接字
sockClient = accept(sockServer, (SOCKADDR*)&addrClient, &len);
//接收並列印客戶端數據
recv(sockClient, recvBuf, 100, 0);
printf("%s\n", recvBuf);
// 所以此處,應該把sockServer改為sockClient
send(/*sockServer*/sockClient, sendBuf, 100, 0);
PS:伺服器客戶端通信,是要保持伺服器與客戶端的連接。
而不能這樣立即關閉,如果設置不對,立即關閉,緩沖區的數據是會丟失的。那客戶端也就不會再收到數據了。
你可以加Sleep(10000);來測是通信過程
//關閉socket
closesocket(sockClient);
5、求一個最簡單的c# C/S Socket 伺服器端實例 非同步
1.簡單伺服器端
/*
using System.Data;
using System.Net.Sockets;
using System.Net;
using System.Threading;
private static int port = %%2;
private static Thread thThreadRead;
private static TcpListener TcpListen;
private static bool bListener = true;
private static Socket stRead;
*/
private static void Listen()
{
try
{
TcpListen = new TcpListener(port);
TcpListen.Start();
stRead = TcpListen.AcceptSocket();
EndPoint tempRemoteEP = stRead.RemoteEndPoint;
IPEndPoint tempRemoteIP = (IPEndPoint)tempRemoteEP;
IPHostEntry host = Dns.GetHostByAddress(tempRemoteIP.Address);
string sHostName = host.HostName;
while (bListener)
{
stRead.Send(Encoding.ASCII.GetBytes(%%1));
string sTime = DateTime.Now.ToShortTimeString();
Byte[] byRead = new Byte[1024];
int iRead = stRead.ReceiveFrom(byRead, ref tempRemoteEP);
Byte[] byText = new Byte[iRead];
Array.Copy(byRead, 0, byText, 0, iRead);
string line = System.Text.Encoding.Default.GetString(byRead);
}
}
catch (System.Security.SecurityException)
{
//監聽失敗
}
}
thThreadRead = new Thread(new ThreadStart(Listen));
thThreadRead.Start();
2.簡單客戶端
/*
using System.Data;
using System.Net.Sockets;
using System.Net;
private static IPEndPoint dateTimeHost;
*/
string hostIPString=%%1;
string hostPortString=%%2;
IPAddress hostIP=IPAddress.Parse(hostIPString);
dateTimeHost=new IPEndPoint(hostIP,Int32.Parse(hostPortString));
Socket conn=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
conn.Connect(dateTimeHost);
int bytes=0;
Byte[] RecvBytes=new Byte[256];
bytes=conn.Receive(RecvBytes,RecvBytes.Length,0);
string RecvString=Encoding.ASCII.GetString(RecvBytes,0,bytes);
Console.WriteLine(RecvString);
conn.Shutdown(SocketShutdown.Both);
conn.Close();
3.獲得本機IP
//using System.Net;
IPAddress[] addressList = Dns.GetHostByName(Dns.GetHostName()).AddressList;
string %%1=null;
for (int i = 0; i < addressList.Length; i++)
{
%%1 += addressList[i].ToString();
}
5.點對點通信
/*
using System.Data;
using System.Net.Sockets;
using System.Net;
using System.Threading;
*/
Thread th;
TcpListener tpListen1;
bool listenerRun=true;
NetworkStream tcpStream;
StreamWriter reqStreamW;
TcpClient tcpc;
Socket skSocket;
protected void Listen()
{
try{
tpListen1=new TcpListener(Int32.Parse(%%2));
tpListen1.Start();
skSocket=tpListen1.AcceptSocket();
EndPoint tempRemoteEP=skSocket.RemoteEndPoint;
IPEndPoint tempRemoteIP=(IPEndPoint)tempRemoteEP;
IPHostEntry host=Dns.GetHostByAddress(tempRemoteIP.Address);
string HostName=host.HostName;
while(listenerRun)
{
Byte[] stream=new Byte[1024];
string time=DateTime.Now.ToString();
int i=skSocket.ReceiveFrom(stream,ref tempRemoteEP);
string %%5=Encoding.UTF8.GetString(stream);
//指定編碼,從緩沖區中解析出內容
//time+" "+HostName+":"
}
}
catch(Security.SecurityException)
{
//防火牆安全錯誤!
}
try{
string sMsg=%%4;
string MyName=Dns.GetHostName();
reqStreamW=new StreamWriter(tcpStream);
reqStreamW.Write(sMsg);
reqStreamW.Flush();
string time=DateTime.Now.ToString();
//顯示傳送的數據和時間
//time+" "+MyName+":"
//sMsg
}
catch(Exception)
{
//無法發送信息到目標計算機!
}
protected override void Dispose(bool disposing)
{
try{
listenerRun=false;
th.Abort();
th=null;
tpListen1.Stop();
skSocket.Close();
tcpc.Close();
}
catch{}
if(disposing && component!=null)
{
components.Dispose();
}
}
base.Dispose(disposing);
}
16.聊天室伺服器端邏輯
using System.Data;
using System.Net.Sockets;
using System.Net;
using System.Threading;
using System.Collections;
class Server
{
private static List<Socket> li = new ArrayList<Socket>();
private static TcpListener TcpListen;
private static Socket stRead;
public Server(int port)
{
try
{
TcpListen = new TcpListener(port);
TcpListen.Start();
}
catch (Exception) { }
}
public List<TcpListener> Li()
{
get{
return li;
};
set{
li=value;
};
}
public void start()
{
while (true)
{
Socket s;
try
{
stRead = TcpListen.AcceptSocket();
li.Add(TcpListen);
new Service(this, s).start();
}
catch (Exception e) { }
}
}
static void main(string[] args)
{
new Server(8888).start();
}
}
class Service
{
private static Socket stRead;
private static bool bListener = true;
private static TcpListener TcpListen;
public Service(Server server, Socket client)
{
TcpClient tcpc;
Socket stSend = null;
bool tcpConnect = false;
try
{
stSend = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
EndPoint tempRemoteEP = stSend.RemoteEndPoint;
IPEndPoint tempRemoteIP = (IPEndPoint)tempRemoteEP;
EndPoint epTemp = (EndPoint)tempRemoteIP;
stSend.Connect(epTemp);
tcpConnect = true;
}
catch (Exception)
{
//MessageBox.Show("目標計算機拒絕了連接請求!");
}
finally
{
if (tcpConnect)
{
stSend.Close();
}
}
}
public static void run()
{
while (true)
{
stRead = TcpListen.AcceptSocket();
EndPoint tempRemoteEP = stRead.RemoteEndPoint;
IPEndPoint tempRemoteIP = (IPEndPoint)tempRemoteEP;
IPHostEntry host = Dns.GetHostByAddress(tempRemoteIP.Address);
string sHostName = host.HostName;
while (bListener)
{
string sTime = DateTime.Now.ToShortTimeString();
Byte[] byRead = new Byte[1024];
int iRead = stRead.ReceiveFrom(byRead, ref tempRemoteEP);
Byte[] byText = new Byte[iRead];
Array.Copy(byRead, 0, byText, 0, iRead);
string line = System.Text.Encoding.Default.GetString(byRead);
}
}
}
static void Main(string[] args)
{
}
}
17.聊天室客戶端邏輯
/*
類似qq聊天工具
你看看。。
這是客服端的代碼:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Net;
using System.Net.Sockets;
namespace demo2
{
public partial class frmTouchWe : Form
{
Thread a;
//發送IP跟埠
private UdpClient udp = new UdpClient("127.0.0.1",9000);
//接收埠
private UdpClient udpSend = new UdpClient(8000);
private IPEndPoint ip = new IPEndPoint(IPAddress.Any,0);
public frmTouchWe()
{
InitializeComponent();
Form. = false;
}
private void frmTouchWe_Load(object sender, EventArgs e)
{ //定義線程開始
a = new Thread(new ThreadStart(Run));
a.Start(); }
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
//客服接收信息。彈出窗體
frmAnswerInfo answerInfo = new frmAnswerInfo();
answerInfo.Show(); }
private void button1_Click(object sender, EventArgs e)
{
//在自己的信息欄中顯示自己的信息
lsbInfo.Items.Add(txtInfo.Text);
//用戶信息內容
string Mes = txtInfo.Text;
//用戶信息
string mes = "用戶:"+Program.user.id+"("+Program.user.name+")"+" " + time;
//轉換成位元組
byte[] b = UTF8Encoding.UTF8.GetBytes(Mes);
byte[] bb = UTF32Encoding.UTF8.GetBytes(mes);
//發送信息
udp.Send(bb, bb.Length);
udp.Send(b, b.Length);
txtInfo.Text = "";
}
//循環接受客服發來的信息
private void Run()
{
while (true)
{
byte[] b = udpSend.Receive(ref ip);
string mes = UTF8Encoding.UTF8.GetString(b);
lsbInfo.Items.Add(mes);
}
}
private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
private void button3_Click_1(object sender, EventArgs e)
{
//清空所有項
lsbInfo.Items.Clear();
}
}
}
下面是伺服器端的代碼
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Net;
using System.Net.Sockets;
namespace demo2
{
public partial class frmAnswerInfo : Form
{
//定義一條線程,用來循環接收客戶發來的信息
Thread a;
//定義另一條線程,用來升起窗體
Thread b;
//發送到信息的地址
private UdpClient udpSend = new UdpClient("127.0.0.1",8000);
//接收埠
private UdpClient udp = new UdpClient(9000);
private IPEndPoint ip = new IPEndPoint(IPAddress.Any,0);
public frmAnswerInfo()
{
InitializeComponent();
Form. = false;
}
//循環接收信息
private void Run()
{
while (true)
{
byte[] b = udp.Receive(ref ip);
string mes = UTF8Encoding.UTF8.GetString(b);
lsbInfo.Items.Add(mes);
}
}
private void frmAnswerInfo_Load(object sender, EventArgs e)
{
//設置窗體的位置屬性(窗體載入時候慢慢從右下角升上來~類似qq廣告~~)
this.Top = Screen.PrimaryScreen.WorkingArea.Height;
this.Left = Screen.PrimaryScreen.WorkingArea.Width - this.Width;
//設置窗體的名字
a = new Thread(new ThreadStart(Run));
b = new Thread(new ThreadStart(run));
//開始線程
a.Start();
b.Start();
}
//用戶點擊談話時顯示該窗體
private void run()
{
while (true)
{
this.Top = this.Top - 10;
Thread.Sleep(100);
if (Screen.PrimaryScreen.WorkingArea.Height - this.Height >= this.Top)
{
break;
}
}
}
//發送按鈕編碼
private void button1_Click(object sender, EventArgs e)
{
//獲取當前時間
DateTime time = DateTime.Now;
//在自己的信息欄中顯示自己發出去的信息
lsbInfo.Items.Add("在線客服:"+time);
lsbInfo.Items.Add(txtInfo.Text);
//在客戶端顯示自己的信息標題
string mes = "在線客服:"+time;
//信息內容
string Mes = txtInfo.Text;
//發送信息標題
byte[] b = UTF8Encoding.UTF8.GetBytes(mes);
//發送信息內容
byte[] bb = UTF8Encoding.UTF8.GetBytes(Mes);
udpSend.Send(b, b.Length);
udpSend.Send(bb,bb.Length);
txtInfo.Text = "";
}
private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
private void button3_Click(object sender, EventArgs e)
{
//清除所有項
lsbInfo.Items.Clear();
}
}
}
*/
6、linux c socket 客戶端循環十次向伺服器發送數據(tcp連接),為啥只能接受第一次的?求代碼
只是做這些動作的話不需要多線程
找了下以前寫的 改成了你說的10次發送
client.c:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<errno.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
int main(int argc,char **argv)
{
char wbuf[] = "hello server";
char rbuf[128];
int i;
int sock;
struct sockaddr_in server = {0};
struct timeval timeo;
timeo.tv_sec = 0;
timeo.tv_usec = 1000 * 1000; //
socklen_t len = sizeof(timeo);
if( argc != 2)
{
printf("usage: ./client <ipaddress>\n");
return -1;
}
sock = socket(AF_INET, SOCK_STREAM, 0);
if(sock < 0)
{
perror("Create TCP Socket");
return -1;
}
setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, &timeo, len);
server.sin_family = AF_INET;
server.sin_port = htons(30000);
inet_pton(AF_INET, argv[1], &(server.sin_addr));
int res = connect(sock, (struct sockaddr*)&server, sizeof(server));
if (res < 0)
{
if(res == EINPROGRESS)
perror("connecting stream socket time out:");
else
perror("connecting stream socket error:");
close(sock);
return -1;
}
else
{
printf("Connect Server@%s\n",argv[1]);
for(i=0;i<10;i++)
{
int wsize = send(sock,wbuf,sizeof(wbuf),0);
if(wsize<=0)
{
perror("write error:");
close(sock);
return -1;
}
printf("1111111i=%d\n",i);
while(1)
{
int rsize=recv(sock,rbuf,sizeof(rbuf),0);
if(rsize>0)
{
rbuf[rsize]='\0';
printf("recv msg from server: %s\n",rbuf);
break;
}
if(rsize<0)
{
close(sock);
perror("read error:");
return -1;
}
}
}
close(sock);
return 0;
}
}
server.c:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<errno.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
int main(int argc, char** argv)
{
int listenfd, connfd;
struct sockaddr_in servaddr = {0};
char rbuf[128];
char wbuf[] = "hello client";
int n;
if( (listenfd = socket(AF_INET, SOCK_STREAM, 0)) == -1 )
{
perror("Create TCP Socket");
return -1;
}
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(30000);
if( bind(listenfd, (struct sockaddr*)&servaddr, sizeof(servaddr)) == -1)
{
perror("bind socket error:");
return -1;
}
if( listen(listenfd, 10) == -1)
{
perror("listen socket error:");
return -1;
}
printf("======waiting for client's request======\n");
while(1)
{
if( (connfd = accept(listenfd, (struct sockaddr*)NULL, NULL)) == -1)
{
perror("accept socket error:");
continue;
}
while(1)
{
n = recv(connfd, rbuf, sizeof(rbuf), 0);
if(n>0)
{
rbuf[n] = '\0';
printf("recvmsg from client: %s\n", rbuf);
n = send(connfd, wbuf, sizeof(wbuf),0);
if(n<=0)
{
perror("sned error:");
close(connfd);
break;
}
}
else if(n < 0)
{
perror("recv error:");
close(connfd);
break;
}
}
close(connfd);
}
close(listenfd);
return 0;
}
運行的時候 client
./client 你的serverip
埠我用的30000 寫死在程序里了
7、C語言socket編程要怎麼實現伺服器可以發消息給客戶端?
先要理解socket是什麼?
簡單的說socket是一個全雙工的通信通道,
即使用TCP或者UDP通信時均可以在發送消息的同時接受消息,
它不區分是否是伺服器。
根據這個概念你的問題就很好回答。
》當客戶端與伺服器連接後。有什麼方法使伺服器可以隨時隨地發消息給客戶端?
》我現在只能。客戶端發個消息給伺服器。伺服器才能發個消息給客戶端。也就是說客戶端不發消息。伺服器就沒法發消息給客戶端。
》求大牛給個思路。當連接後。客戶端與伺服器雙方可以隨時隨地通信!
使用多線程,一個維持接受邏輯,一個維持送信邏輯,即可完成同時接受及發送。
客戶端及伺服器端均做上述設置。
而你的做法是在一個線程中執行接受與送信,因此只能按照順序邏輯完成接收與送信。
關鍵點是多線程。
8、用c語言寫socket編寫服務端
這個可以有的。我截圖給你看看
研究了這么久。現在也能獨立完成一個簡單的sock了。QQ2638512393.歡迎你加我一起學習探討。呵呵
9、C語言編程socket有個客服端和服務端怎麼建文件並且運行
網路的Socket數據傳輸是一種特殊的I/O,Socket也是一種文件描述符。Socket也具有一個類似於打開文件的函數調用Socket(),該函數返回一個整型的Socket描述符,隨後的連接建立、數據傳輸等操作都是通過該Socket實現的。
下面用Socket實現一個windows下的c語言socket通信例子,這里我們客戶端傳遞一個字元串,伺服器端進行接收。
【伺服器端】
#include "stdafx.h"
#include <stdio.h>
#include <winsock2.h>
#include <winsock2.h>
#define SERVER_PORT 5208 //偵聽埠
void main()
{
WORD wVersionRequested;
WSADATA wsaData;
int ret, nLeft, length;
SOCKET sListen, sServer; //偵聽套接字,連接套接字
struct sockaddr_in saServer, saClient; //地址信息
char *ptr;//用於遍歷信息的指針
//WinSock初始化
wVersionRequested=MAKEWORD(2, 2); //希望使用的WinSock DLL 的版本
ret=WSAStartup(wVersionRequested, &wsaData);
if(ret!=0)
{
printf("WSAStartup() failed!\n");
return;
}
//創建Socket,使用TCP協議
sListen=socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sListen == INVALID_SOCKET)
{
WSACleanup();
printf("socket() faild!\n");
return;
}
//構建本地地址信息
saServer.sin_family = AF_INET; //地址家族
saServer.sin_port = htons(SERVER_PORT); //注意轉化為網路位元組序
saServer.sin_addr.S_un.S_addr = htonl(INADDR_ANY); //使用INADDR_ANY 指示任意地址
//綁定
ret = bind(sListen, (struct sockaddr *)&saServer, sizeof(saServer));
if (ret == SOCKET_ERROR)
{
printf("bind() faild! code:%d\n", WSAGetLastError());
closesocket(sListen); //關閉套接字
WSACleanup();
return;
}
//偵聽連接請求
ret = listen(sListen, 5);
if (ret == SOCKET_ERROR)
{
printf("listen() faild! code:%d\n", WSAGetLastError());
closesocket(sListen); //關閉套接字
return;
}
printf("Waiting for client connecting!\n");
printf("Tips: Ctrl+c to quit!\n");
//阻塞等待接受客戶端連接
while(1)//循環監聽客戶端,永遠不停止,所以,在本項目中,我們沒有心跳包。
{
length = sizeof(saClient);
sServer = accept(sListen, (struct sockaddr *)&saClient, &length);
if (sServer == INVALID_SOCKET)
{
printf("accept() faild! code:%d\n", WSAGetLastError());
closesocket(sListen); //關閉套接字
WSACleanup();
return;
}
char receiveMessage[5000];
nLeft = sizeof(receiveMessage);
ptr = (char *)&receiveMessage;
while(nLeft>0)
{
//接收數據
ret = recv(sServer, ptr, 5000, 0);
if (ret == SOCKET_ERROR)
{
printf("recv() failed!\n");
return;
}
if (ret == 0) //客戶端已經關閉連接
{
printf("Client has closed the connection\n");
break;
}
nLeft -= ret;
ptr += ret;
}
printf("receive message:%s\n", receiveMessage);//列印我們接收到的消息。
}
// closesocket(sListen);
// closesocket(sServer);
// WSACleanup();
}
【客戶端】
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <winsock2.h>
#define SERVER_PORT 5208 //偵聽埠
void main()
10、誰能用C語言寫個最簡單socket通信服務端和客戶端示例
網路的Socket數據傳輸是一種特殊的I/O,Socket也是一種文件描述符。Socket也具有一個類似於打開文件的函數調用Socket(),該函數返回一個整型的Socket描述符,隨後的連接建立、數據傳輸等操作都是通過該Socket實現的。
下面用Socket實現一個windows下的c語言socket通信例子,這里我們客戶端傳遞一個字元串,伺服器端進行接收。
【伺服器端】
#include "stdafx.h"
#include <stdio.h>
#include <winsock2.h>
#include <winsock2.h>
#define SERVER_PORT 5208 //偵聽埠
void main()