socket编程:tcp client端如何获得已经发送出去但是还没有收到对端确认的TCP数据数量

socket编程:tcp client端如何获得已经发送出去但是还没有收到对端确认的TCP数据数量 恳请大神帮忙!

1个回答

应用层得不到这个信息。这些tcp协议栈内部的数据,对上层没有接口。应用层如果需要明确对方接收完了多少数据,应该在应用层协议中增加确认机制,对方收到多少数据,就给个应答明确接收了多少字节。

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
Socket编程初级问题,关于消息发送
本人刚接触java以及socket编程,入门级水平。 现已知客户端跟服务端java代码如下: //服务端 import java.net.*; // for Socket, ServerSocket, and InetAddress import java.io.*; // for IOException and Input/OutputStream public class TCP_Server { private static final int BUFSIZE = 32; // Size of receive buffer public static void main(String[] args) throws IOException { if (args.length != 1) // Test for correct # of args throw new IllegalArgumentException("Parameter(s): <Port>"); int servPort = Integer.parseInt(args[0]); // Create a server socket to accept client connection requests ServerSocket servSock = new ServerSocket(servPort); int recvMsgSize; // Size of received message byte[] byteBuffer = new byte[BUFSIZE]; // Receive buffer for (;;) { // Run forever, accepting and servicing connections Socket clntSock = servSock.accept(); // Get client connection System.out.println("Handling client at " + clntSock.getInetAddress().getHostAddress() + " on port " + clntSock.getPort()); InputStream in = clntSock.getInputStream(); OutputStream out = clntSock.getOutputStream(); // Receive until client closes connection, indicated by -1 return while ((recvMsgSize = in.read(byteBuffer)) != -1) /* (添加代码,企图改变字符串顺序) */ out.write(byteBuffer, 0, recvMsgSize); clntSock.close(); // Close the socket. We are done with this client! } /* NOT REACHED */ } } ``` ``` //客户端 import java.net.*; // for Socket import java.io.*; // for IOException and Input/OutputStream public class TCPEchoClient { public static void main(String[] args) throws IOException { if ((args.length < 2) || (args.length > 3)) // Test for correct # of args throw new IllegalArgumentException("Parameter(s): <Server> <Word> [<Port>]"); String server = args[0]; // Server name or IP address // Convert input String to bytes using the default character encoding byte[] byteBuffer = args[1].getBytes(); int servPort = (args.length == 3) ? Integer.parseInt(args[2]) : 7; // Create socket that is connected to server on specified port Socket socket = new Socket(server, servPort); System.out.println("Connected to server...sending echo string"); InputStream in = socket.getInputStream(); OutputStream out = socket.getOutputStream(); out.write(byteBuffer); // Send the encoded string to the server // Receive the same string back from the server int totalBytesRcvd = 0; // Total bytes received so far int bytesRcvd; // Bytes received in last read while (totalBytesRcvd < byteBuffer.length) { if ((bytesRcvd = in.read(byteBuffer, totalBytesRcvd, byteBuffer.length - totalBytesRcvd)) == -1) throw new SocketException("Connection close prematurely"); totalBytesRcvd += bytesRcvd; } System.out.println("Received: " + new String(byteBuffer)); socket.close(); // Close the socket and its streams } } ``` ``` 一般情况下,是开两个终端分别运行服务端与客户端, 先执行服务端,显示如下: g136@ispc29Lx:~$ java TCP_Server 50000 再执行客户端,依次输入IP 字符串 port号,显示如下 g136@ispc29Lx:~$ java TCPEchoClient 150.86.64.169 ab 50000 然后客户端跟服务端都会产生反应,如下: g136@ispc29Lx:~$ java TCP_Server 50000 Handling client at 150.86.64.169 on port 58002 g136@ispc29Lx:~$ java TCPEchoClient 150.86.64.169 ab 50000 Connected to server...sending echo string Received: ab 输入的是ab,服务端原封不动的返回的也是ab,我希望能在服务端添加一段代码,使返回的字符顺序改变成ba;或者把ab变成大写,怎么都行,只是希望能对原字符串进行改变。 第一次提问题,还请多多包涵。
使用TCP编程客户端代码运行起来报错
本人是新手开始学习TCP编程: 如下是客户端的代码 ```package Day23.Internet.TCP; import java.io.IOException; import java.io.OutputStream; import java.net.InetAddress; import java.net.Socket; import java.net.UnknownHostException; //TCP的客户端 public class Demo1Client { //TCP的客户端使用步骤 public static void main(String[] args) throws IOException { //1.建立TCP的服务 Socket socket = new Socket(InetAddress.getLocalHost(), 60000); //2.获取到对应的流对象(获取到Socket 的输出流对象) OutputStream outputStream = socket.getOutputStream(); //3.利用输出流对案发把数据写出即可 outputStream.write("服务器你好".getBytes()); System.out.println("发送了!!"); outputStream.flush(); //4.关闭TCP服务 socket.close(); System.out.println("关闭了客户端!!"); } } ``` 以下是服务器的代码 ```package Day23.Internet.TCP; import java.io.IOException; import java.io.InputStream; import java.net.ServerSocket; import java.net.Socket; //TCP的服务端 //使用ServerSocket public class Demo1Server { public static void main(String[] args) { try { // 1.建立TCP的服务端,并监听一个端口 ServerSocket serverSocket = new ServerSocket(60000); // 2.获取输入溜对象,读取客户端发送的信息 //ServerSocket并没有下面的方法 但是Socket有呀 // serverSocket. getInputStream() //可以先利用ServerSocet的accept方法获取连接到的Socket对象 Socket socket = serverSocket.accept(); System.out.println("hehe"); InputStream inputStream = socket.getInputStream(); byte[] buf = new byte[1024]; int length = inputStream.read(buf); System.out.println(new String()); serverSocket.close(); } catch (IOException e) { e.printStackTrace(); } } } ``` 运行起来后 报错如下(是客户端的问题) ``` Exception in thread "main" java.net.ConnectException: Connection timed out: connect at java.net.DualStackPlainSocketImpl.connect0(Native Method) at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source) at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source) at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source) at java.net.AbstractPlainSocketImpl.connect(Unknown Source) at java.net.PlainSocketImpl.connect(Unknown Source) at java.net.SocksSocketImpl.connect(Unknown Source) at java.net.Socket.connect(Unknown Source) at java.net.Socket.connect(Unknown Source) at java.net.Socket.<init>(Unknown Source) at java.net.Socket.<init>(Unknown Source) ```
java的socket编程和网络协议的关系的一些疑问
用socket编程时,没有指定应用层协议就可以直接把client socket的数据发出去到server socket,socket编程不需要使用应用层协议吗?为啥用到了传输层协议(默认好像是TCP)却不用应用层协议?
TCP网络编程:服务器端的while为什么不能循环结束
功能:通过服务器将e盘下的文件复制一份 疑惑点:客户端已经将文件数据写入输出流中,服务端读取while不能结束原因 ``` import java.io.*; import java.net.*; 客户端 public class client4 { public static void main(String[] args)throws Exception { Socket s=new Socket("192.168.1.103",10003); //目的:服务端 BufferedWriter bufw=new BufferedWriter(new OutputStreamWriter(s.getOutputStream())); BufferedReader bufr=new BufferedReader(new FileReader("E:\\Circle.java")); String line=null; while((line=bufr.readLine())!=null) { bufw.write(line); bufw.newLine(); bufw.flush(); } BufferedReader bufrS=new BufferedReader(new InputStreamReader(s.getInputStream())); String str=bufrS.readLine(); System.out.println(str); bufr.close(); s.close(); } } ``` ``` //服务器端 import java.io.*; import java.net.*; public class server4 { public static void main(String[] args)throws Exception { ServerSocket ss=new ServerSocket(10003); Socket s=ss.accept(); String ip=s.getInetAddress().getHostAddress(); System.out.println(ip+".....connect"); //从客户端读数据 BufferedReader bufr=new BufferedReader(new InputStreamReader(s.getInputStream())); //写入文件中() BufferedWriter bufw=new BufferedWriter(new FileWriter("e:\\copy.java")); String line=null; while((line=bufr.readLine())!=null) { bufw.write(line); bufw.newLine(); bufw.flush(); } BufferedWriter bufwS=new BufferedWriter (new OutputStreamWriter(s.getOutputStream())); bufwS.write("数据复制成功"); bufwS.newLine(); bufwS.flush(); bufw.close(); s.close(); } } ```
socket编程客户端连接失败
想用socket通信,没法解决客户端连接失败,代码是一本书上的实例,书上的都运行不成功吗,大家帮看下问题在那里,谢谢了![图片说明](https://img-ask.csdn.net/upload/201507/13/1436783188_607205.png) 代码如下: 服务器端:################################################### #include<stdio.h> #include<winsock.h> /*引入winsock头文件*/ int main() { /*-----------------------------------------*/ /*------------定义变量---------------------*/ /*-----------------------------------------*/ char Sendbuf[100]; /*发送数据的缓冲区*/ char Receivebuf[100]; /*接受数据的缓冲区*/ int SendLen; /*发送数据的长度*/ int ReceiveLen; /*接收数据的长度*/ int Length; /*表示SOCKADDR的大小*/ SOCKET socket_server; /*定义服务器套接字*/ SOCKET socket_receive; /*定义用于连接套接字*/ SOCKADDR_IN Server_add; /*服务器地址信息结构*/ SOCKADDR_IN Client_add; /*客户端地址信息结构*/ WORD wVersionRequested; /*字(word):unsigned short*/ WSADATA wsaData; /*库版本信息结构*/ int error; /*表示错误*/ /*-----------------------------------------*/ /*------------初始化套接字库---------------*/ /*-----------------------------------------*/ /*定义版本类型。将两个字节组合成一个字,前面是第字节,后面是高字节*/ wVersionRequested = MAKEWORD( 2, 2 ); /*加载套接字库,初始化Ws2_32.dll动态链接库*/ error = WSAStartup( wVersionRequested, &wsaData); if(error!=0) { printf("加载套接字失败!"); return 0; /*程序结束*/ } /*判断请求加载的版本号是否符合要求*/ if ( LOBYTE( wsaData.wVersion ) != 2 || HIBYTE( wsaData.wVersion ) != 2 ) { WSACleanup( ); /*不符合,关闭套接字库*/ return 0; /*程序结束*/ } /*-----------------------------------------*/ /*------------设置连接地址-----------------*/ /*-----------------------------------------*/ Server_add.sin_family=AF_INET;/*地址家族,对于必须是AF_INET,注意只有它不是网络网络字节顺序*/ Server_add.sin_addr.S_un.S_addr=htonl(INADDR_ANY);/*主机地址*/ Server_add.sin_port=htons(5000);/*端口号*/ /*------------创建套接字-------------------*/ /*AF_INET表示指定地址族,SOCK_STREAM表示流式套接字TCP,特定的地址家族相关的协议。*/ socket_server=socket(AF_INET,SOCK_STREAM,0); /*-----------------------------------------*/ /*---绑定套接字到本地的某个地址和端口上----*/ /*-----------------------------------------*/ /*socket_server为套接字,(SOCKADDR*)&Server_add为服务器地址*/ if(bind(socket_server,(SOCKADDR*)&Server_add,sizeof(SOCKADDR) )==SOCKET_ERROR) { printf("绑定失败\n"); } /*-----------------------------------------*/ /*------------设置套接字为监听状态---------*/ /*-----------------------------------------*/ /*监听状态,为连接做准备,最大等待的数目为5*/ if(listen(socket_server,5)<0) { printf("监听失败\n"); } /*-----------------------------------------*/ /*------------接受连接---------------------*/ /*-----------------------------------------*/ Length=sizeof(SOCKADDR); /*接受客户端的发送请求,等待客户端发送connect请求*/ socket_receive=accept(socket_server,(SOCKADDR*)&Client_add,&Length); if(socket_receive==SOCKET_ERROR) { printf("接受连接失败"); } /*-----------------------------------------*/ /*--------------进行聊天-------------------*/ /*-----------------------------------------*/ while(1) /*无限循环*/ { /*--------接收数据---------*/ ReceiveLen =recv(socket_receive,Receivebuf,100,0); if(ReceiveLen<0) { printf("接收失败\n"); printf("程序退出\n"); break; } else { printf("client say: %s\n",Receivebuf); } /*--------发送数据---------*/ printf("please enter message:"); scanf("%s",Sendbuf); SendLen=send(socket_receive,Sendbuf,100,0); if(SendLen<0) { printf("发送失败\n"); } } /*-----------------------------------------*/ /*---------释放套接字,关闭动态库----------*/ /*-----------------------------------------*/ closesocket(socket_receive); /*释放客户端的套接字资源*/ closesocket(socket_server);/*释放套接字资源*/ WSACleanup();/*关闭动态链接库*/ return 0; } 客户端:##################################################### #include<stdio.h> #include<winsock.h> /*引入winsock头文件*/ int main() { /*-----------------------------------------*/ /*------------定义变量---------------------*/ /*-----------------------------------------*/ char Sendbuf[100]; /*发送数据的缓冲区*/ char Receivebuf[100]; /*接受数据的缓冲区*/ int SendLen; /*发送数据的长度*/ int ReceiveLen; /*接收数据的长度*/ SOCKET socket_send; /*定义套接字*/ SOCKADDR_IN Server_add; /*服务器地址信息结构*/ WORD wVersionRequested; /*字(word):unsigned short*/ WSADATA wsaData; /*库版本信息结构*/ int error; /*表示错误*/ /*-----------------------------------------*/ /*------------初始化套接字库---------------*/ /*-----------------------------------------*/ /*定义版本类型。将两个字节组合成一个字,前面是第字节,后面是高字节*/ wVersionRequested = MAKEWORD( 2, 2 ); /*加载套接字库,初始化Ws2_32.dll动态链接库*/ error = WSAStartup( wVersionRequested, &wsaData); if(error!=0) { printf("加载套接字失败!"); return 0; /*程序结束*/ } /*判断请求加载的版本号是否符合要求*/ if ( LOBYTE( wsaData.wVersion ) != 2 || HIBYTE( wsaData.wVersion ) != 2 ) { WSACleanup( ); /*不符合,关闭套接字库*/ return 0; /*程序结束*/ } /*-----------------------------------------*/ /*------------设置服务器地址---------------*/ /*-----------------------------------------*/ Server_add.sin_family=AF_INET;/*地址家族,对于必须是AF_INET,注意只有它不是网络网络字节顺序*/ /*服务器的地址,将一个点分十进制表示为IP地址,inet_ntoa是将地址转成字符串*/ Server_add.sin_addr.S_un.S_addr = inet_addr("192.168.1.238"); Server_add.sin_port=htons(5000);/*端口号*/ /*-----------------------------------------*/ /*-------------进行连接服务器--------------*/ /*-----------------------------------------*/ /*客户端创建套接字,但是不需要绑定的,只需要和服务器建立起连接就可以了,*/ /*socket_sendr表示的是套接字,Server_add服务器的地址结构*/ socket_send=socket(AF_INET,SOCK_STREAM,0); /*-----------------------------------------*/ /*-------------创建用于连接的套接字--------*/ /*-----------------------------------------*/ /*AF_INET表示指定地址族,SOCK_STREAM表示流式套接字TCP,特定的地址家族相关的协议。*/ if(connect(socket_send,(SOCKADDR*)&Server_add,sizeof(SOCKADDR)) == SOCKET_ERROR) { printf("连接失败!\n"); } /*-----------------------------------------*/ /*--------------进行聊天-------------------*/ /*-----------------------------------------*/ while(1) /*无限循环*/ { /*---------------发送数据过程----------*/ printf("please enter message:"); scanf("%s",Sendbuf); SendLen = send(socket_send,Sendbuf,100,0); /*发送数据*/ if(SendLen < 0) { printf("发送失败!\n"); } /*--------------接收数据过程---------------*/ ReceiveLen =recv(socket_send,Receivebuf,100,0); /*接受数据*/ if(ReceiveLen<0) { printf("接收失败\n"); printf("程序退出\n"); break; } else { printf("Server say: %s\n",Receivebuf); } } /*-----------------------------------------*/ /*---------释放套接字,关闭动态库----------*/ /*-----------------------------------------*/ closesocket(socket_send);/*释放套接字资源*/ WSACleanup();/*关闭动态链接库*/ return 0; }
c++的socket编程,无客户端连接accept却不阻塞,直接返回了,怎么解决
以下是服务端的代码: ``` #include "stdafx.h" #include "winsock2.h" #include "iostream" #pragma comment (lib,"ws2_32") using namespace std; int _tmain(int argc, _TCHAR* argv[]) { WSADATA wsadata; WSAStartup(MAKEWORD(2, 2), &wsadata); cout << "开始创建套接字\n"; SOCKET s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); struct sockaddr_in saddrin; saddrin.sin_addr.S_un.S_addr = inet_addr("INADDR_ANY"); saddrin.sin_port = htons(9100); cout << "开始绑定\n"; bind(s, (sockaddr *)&saddrin, sizeof(saddrin)); cout << "开始监听\n"; listen(s, SOMAXCONN); struct sockaddr_in sClient; int num = sizeof(sClient); SOCKET client= accept(s, (sockaddr *)&sClient, &num); if (client) { cout << "已接受来自客户端的连接\n"; cout << sClient.sin_port<<'\n'; cout<< inet_ntoa(sClient.sin_addr)<<'\n'; char msg[MAXBYTE] = { 0 }; recv(client, msg, sizeof(msg), 0); cout << msg; strcpy_s(msg, "this is a reply for the test\n"); send(client, msg, strlen(msg) + sizeof(char), 0); cout << "已发送消息\n"; } else { cout << "无客户端的连接"; } system("PAUSE"); return 0; } ``` 运行结果如下: ![图片说明](https://img-ask.csdn.net/upload/201603/05/1457150555_147664.png) 启动了服务端,客户端都没启动,就直接执行完返回了,accept那里不是应该阻塞,等待客户端的连接的吗?即使同时启动客户端和服务端也是这样的结果,请问应该怎么解决?
socket编程发送消息出现socket closed求大神,急
import java.io.DataInputStream; import java.io.EOFException; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; public class Server { ServerSocket ss; Socket s ; Clients clients; DataInputStream dis; boolean startServer = false; public void startServer(){ try { ss = new ServerSocket(8888);//8888是TCP端口号 startServer = true; while(startServer){ s = ss.accept(); System.out.println(" connected!"); clients = new Clients(s); new Thread(clients).start(); } }catch(IOException e){ e.printStackTrace(); }finally{ try { ss.close(); } catch (IOException e) { e.printStackTrace(); } } } public static void main(String[] args) { new Server().startServer(); } } class Clients implements Runnable{//包装类,把外部连接的client包装 private Socket s; private boolean isConnected = false ; private DataInputStream dis; public Clients(Socket s) { this.s = s; try { isConnected = true; dis = new DataInputStream(s.getInputStream()); } catch (IOException e) { e.printStackTrace(); } } @Override public void run() { while(isConnected){ try { String str = dis.readUTF();//阻塞:它会一直等待 System.out.println(str); } catch (EOFException e){ System.out.println("Client is closed!"); }catch (IOException e1) { e1.printStackTrace(); }finally{ try { if(dis!=null) { dis.close(); }else{ ; } if(s!=null) { s.close(); }else{ ; } } catch (IOException e) { e.printStackTrace(); } } } } } import java.io.DataOutputStream; import java.io.IOException; import java.io.PrintWriter; import java.net.Socket; import java.net.UnknownHostException; import java.util.Scanner; public class Client { Socket s; PrintWriter pw; DataOutputStream dos; String line = ""; Scanner reader = new Scanner(System.in); public void startClient(){ try { s = new Socket("127.0.0.1", 8888); dos = new DataOutputStream(s.getOutputStream()); System.out.println("connected"); do{ System.out.print("please input:"); line = reader.next(); dos.writeUTF(line); dos.flush(); }while(!line.equals("bye")); dos.close(); s.close(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) { new Client().startClient(); } } java.net.SocketException: socket closed at java.net.SocketInputStream.socketRead0(Native Method) at java.net.SocketInputStream.read(Unknown Source) at java.net.SocketInputStream.read(Unknown Source) at java.net.SocketInputStream.read(Unknown Source) at java.io.DataInputStream.readUnsignedShort(Unknown Source) at java.io.DataInputStream.readUTF(Unknown Source) at java.io.DataInputStream.readUTF(Unknown Source) at Clients.run(Server.java:75) at java.lang.Thread.run(Unknown Source)
vb.netSOCKET,服务端如何获取刚刚断了的客户端IP地址?
SOCKET编程,TCP上百个客户端,客户端突然断了的时候(比如停电、死机),服务端我用try - catch ,但是在服务端如何知道(获得、判断)已经断了(刚刚断掉的)的是哪个客户端(IP地址)。 断的时候这里报错:try BytesRead = _Client.GetStream.EndRead(ar) catch ,如何这这里获取客户端的IP地址?
求助,C# winform实现socket接收客户端数据,总是丢数据。
程序主体是client端发送数据给server端,server那边接收到信息就发送一条固定的确认信息给client。 出现的问题就是运行的时候会固定丢掉第二次返回的数据,第一次和其他时候的都正常。打断点调试的时候也是正常的,很懵啊。。 感觉跟UI刷新有关,却又解决不了。另开线程接收也会有这个问题。贴上代码,求助大神。 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.Net; using System.Net.Sockets; using System.Threading; namespace SocketDemo_Client { public partial class MainForm : Form { public MainForm() { InitializeComponent(); } private Socket soc_client = null; private byte[] socket_buf = null; private Thread t_listener = null; private void MainForm_Load(object sender, EventArgs e) { if (socket_buf == null) { socket_buf = new byte[4096]; } } /// <summary> /// 连接按钮的点击事件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnConnect_Click(object sender, EventArgs e) { IPAddress host_ip = IPAddress.Parse(this.txtIP.Text); IPEndPoint end_ipe = new IPEndPoint(host_ip, Convert.ToInt32(this.txtPort.Text)); soc_client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); soc_client.Connect(end_ipe); this.txtLog.AppendText("连接到" + soc_client.RemoteEndPoint.ToString() + "服务端。。。"); this.txtLog.AppendText(System.Environment.NewLine); } private void btnDisConnect_Click(object sender, EventArgs e) { this.txtLog.AppendText("关闭双向传输通道。。。"); this.txtLog.AppendText(System.Environment.NewLine); soc_client.Shutdown(SocketShutdown.Both); Thread.Sleep(500); this.txtLog.AppendText("关闭Socket对象。。。"); this.txtLog.AppendText(System.Environment.NewLine); soc_client.Close(); } private void btnSendMsg_Click(object sender, EventArgs e) { if (this.txtMsg.Text == "") { MessageBox.Show("输入发送内容啊骚年!"); return; } this.txtLog.AppendText("发送" + this.txtMsg.Text + "到服务端。。。"); this.txtLog.AppendText(System.Environment.NewLine); /* Array.Clear(socket_buf, 0, socket_buf.Length); socket_buf = Encoding.ASCII.GetBytes(this.txtMsg.Text); soc_client.Send(socket_buf); //清空发送框 this.txtMsg.Text = ""; //启动接收监听线程 if (t_listener == null) { t_listener = new Thread(MsgListener); t_listener.Start(); } if (t_listener.ThreadState == ThreadState.Suspended) { t_listener.Resume(); } */ string getStr = ""; getStr = SendAndReceive(this.txtMsg.Text); Thread.Sleep(2000); this.txtLog.AppendText("收到服务端信息:"); this.txtLog.AppendText(System.Environment.NewLine); this.txtLog.AppendText(getStr); this.txtLog.AppendText(System.Environment.NewLine); } /// <summary> /// /// </summary> private string SendAndReceive(string msg) { Array.Clear(socket_buf, 0, socket_buf.Length); socket_buf = Encoding.ASCII.GetBytes(msg); soc_client.Send(socket_buf); //清空发送框 this.txtMsg.Text = ""; string t = ""; soc_client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 500); Array.Clear(socket_buf, 0, socket_buf.Length); try { while (true) { int length = soc_client.Receive(socket_buf); t += Encoding.ASCII.GetString(socket_buf, 0, length); } } catch (SocketException e) { return t; } return t; } /// <summary> /// 接收线程 /// </summary> private void MsgListener() { string get_str = ""; soc_client.SetSocketOption(SocketOptionLevel.Socket,SocketOptionName.ReceiveTimeout,500); while (true) { Array.Clear(socket_buf, 0, socket_buf.Length); try { int length = soc_client.Receive(socket_buf); //接收活动连接发送的数据填充到buffer中 get_str += Encoding.ASCII.GetString(socket_buf, 0, length); //将缓存buffer的byte数据转换成字符串 } catch (SocketException se) { //线程委托去刷新信息 this.Invoke(new MethodInvoker(delegate { this.txtLog.AppendText("收到服务端信息:"); this.txtLog.AppendText(System.Environment.NewLine); this.txtLog.AppendText(get_str); this.txtLog.AppendText(System.Environment.NewLine); get_str = ""; })); //挂起线程 t_listener.Suspend(); continue; } } } } }
c++,socket,没启动客户端,服务端显示已有204.204.204.204的ip连接了
``` #include "stdafx.h" #include "winsock2.h" #include "iostream" #pragma comment (lib,"ws2_32") using namespace std; int _tmain(int argc, _TCHAR* argv[]) { WSADATA wsadata; WSAStartup(MAKEWORD(2, 2), &wsadata); cout << "开始创建套接字\n"; SOCKET s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); struct sockaddr_in saddrin; saddrin.sin_family = AF_INET; saddrin.sin_addr.S_un.S_addr = inet_addr("INADDR_ANY"); saddrin.sin_port = htons(9100); cout << "开始绑定\n"; bind(s, (sockaddr *)&saddrin, sizeof(saddrin)); cout << "开始监听\n"; listen(s, SOMAXCONN); struct sockaddr_in sClient; int num = sizeof(sClient); SOCKET client= accept(s, (sockaddr *)&sClient, &num); if (client) { cout << "已接受来自客户端的连接\n"; cout << sClient.sin_port<<'\n'; cout<< inet_ntoa(sClient.sin_addr)<<'\n'; char msg[MAXBYTE] = { 0 }; recv(client, msg, sizeof(msg), 0); cout << msg; //char msgReply[MAXBYTE ] = { 0 }; strcpy_s(msg, "this is a reply for the test\n"); send(client, msg, strlen(msg) + sizeof(char), 0); cout << "已发送消息\n"; } else { cout << "无客户端的连接"; } system("PAUSE"); return 0; } ``` ![图片说明](https://img-ask.csdn.net/upload/201603/05/1457181067_216641.png) 我的客户端还没启动,只启动了服务端,这个204.204.204.204就连接了,然后就返回了?这个ip是怎么回事?怎么解决?
java socket server
用java编写的一个socket服务端,通过一个tcp测试工具测试这个服务端,发现发送数据给服务端,服务端接收不到,当tcp测试工具断开连接后,测试工具发送的字符串才被服务端接收到,这是为什么? java socket服务端代码 [code="java"] package com.myserver.server; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class MultiThreadServer { private int port = 6666; private ServerSocket serverSocket; private ExecutorService executorService;//线程池 private final int POOL_SIZE = 10;//单个CPU线程池大小 public MultiThreadServer() throws IOException { serverSocket = new ServerSocket(port); //Runtime的availableProcessor()方法返回当前系统的CPU数目. executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * POOL_SIZE); System.out.println("server start"); } public void service() { while (true) { Socket socket = null; try { //接收客户连接,只要客户进行了连接,就会触发accept();从而建立连接 socket = serverSocket.accept(); executorService.execute(new Handler(socket)); Count.add(); System.out.println("client number " + Count.num); } catch (Exception e) { e.printStackTrace(); } } } public static void main(String[] args) throws IOException { new MultiThreadServer().service(); } } class Handler implements Runnable { private Socket socket; public Handler(Socket socket) { this.socket = socket; } public void run() { try { System.out.println("a client connect " + socket.getInetAddress() + ":" + socket.getPort()); PrintWriter writer = new PrintWriter(socket.getOutputStream()); writer.println("connect success"); writer.flush(); BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); String readLine = reader.readLine(); while (true) { if (readLine != null) { System.out.println(readLine); readLine = reader.readLine(); } else { break; } } writer.close(); reader.close(); } catch (IOException e) { System.out.println("a client leave"); Count.sub(); System.out.println("client number " + Count.num); } finally { try { if (socket != null) { socket.close(); } } catch (IOException e) { e.printStackTrace(); } } } } class Count { public static int num = 0; public static void add() { num += 1; } public static void sub() { num -= 1; } } [/code] java服务端状态输出如下 server start client number 1 a client connect /127.0.0.1:50437 affff tcp测试工具截图 [img]http://dl.iteye.com/upload/attachment/526919/4726dc79-31b2-3216-8887-de70efdd80cb.jpg[/img] 补充说明: tcp测试工具能够正常连接到服务端,但是文本数据发送,服务端不会实时显示,只有当测试工具断开连接时,这时,服务端才显示刚才测试工具发送的文本数据
DEVC++中使用winsock2进行TCP编程的客户端无法接收到服务器返回数据的问题
在客户端输入两个数字,发送到服务器端,服务器接收后进行在做和运算,将结果返回给客户端,但现在无法接收到返回数据。客服端连接是没有问题的。 代码如下: 服务端 SOCKET AcceptSocket; sockaddr_in remoteAddr; int nAddrlen = sizeof(remoteAddr); AcceptSocket = accept( s,(SOCKADDR*) &remoteAddr,&nAddrlen); if (AcceptSocket == INVALID_SOCKET) { cout<<"Accept socket fali!"<<endl; ::closesocket(s); ::WSACleanup( ); return 1; } //6.收发数据 //退出标记 BOOL QuitFlag = FALSE; while(!QuitFlag) { //接收数据 int Buffer[1024]={0}; //char Buf[255]; nRetuen = ::recv(AcceptSocket,(char*)&Buffer,1024,QuitFlag); //判断情况 switch (nRetuen) { case 0: { //::closesocket(AcceptSocket); //::closesocket(s); //::WSACleanup( ); cout << "client's connection is closed!" << endl; } break; case SOCKET_ERROR : { //::closesocket(AcceptSocket); //::closesocket(s); //::WSACleanup( ); cout << "server's connection is closed!" << endl; break; } default: { if (Buffer[0] == 0 && Buffer[1] == 0) { QuitFlag = TRUE; } else { int result = Buffer[0] + Buffer[1]; cout <<Buffer[0] <<" + "<<Buffer[1] <<" = " <<result <<endl; //发送数据 send(s,(char*)&result,1024,0); cout<<"send success!"<<endl; } } } } 客户端 int data[1024] = {0}; while (1) { cin >> data[0] >> data[1]; fflush( stdin ); nRetuen = ::send(sockClient,(char*)&data,1024,0); int error = 0; if (nRetuen == SOCKET_ERROR) { error = WSAGetLastError(); cout<<"send fail!"<<endl; } if (data[0] == 0 && data[1] == 0) { cout << " Client will quit!" <<endl; break; } //send(sockClient,(char*)&data[2],sizeof(data[2]),0); //5.接收数据 int sum=0; int recvbuffer[1024]={0}; memset(recvbuffer,0,1024); nRetuen = ::recv(sockClient,(char*)&recvbuffer,1024,0); if(nRetuen > 0) { sum = (int*)&recvbuffer; cout << data[0] << " + " << data[1] << " = " << sum;; } else if (nRetuen == 0) { error = WSAGetLastError(); cout<<"receive fail!"<<endl; } else { cout << "SOCKET_ERROR"<<endl; } } ``` ``` 客户端
套接字编程,使用TCP协议编写服务器程序——绑定错误10038
![图片说明](https://img-ask.csdn.net/upload/201604/07/1459993897_818283.png) 不明白为什么会发生这个错误,求大神指点!具体代码如下 ``` #pragma comment(lib,"ws2_32.lib")//第二版本32位的把lib文件添加到项目中windows套接字的动态链接库 #include<stdio.h> #include<stdlib.h> #include<WinSock2.h> void main(void) { WSADATA wsaData; //定义一个data,data用来初始化windows套接字socket(***---这是第一步---***) SOCKET ListeningSocket; //定义一个套接字 SOCKET NewConnection; //定义一个客户端套接字 SOCKADDR_IN ServerAddr; //创建服务端地址 SOCKADDR_IN ClientAddr; //创建客户端地址 int ClientAddrLen; //声明客户端地址长度 int Ret; //检查初始化是否成功,接受了多少个字节 int Port=5150; char DataBuffer[1024]; if((Ret=WSAStartup(MAKEWORD(2,2),&wsaData))!=0) { printf("WSAStartup failed with error %d\n",Ret);//初始化失败返回错误信息 system("pause"); return; } if((ListeningSocket=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP)==INVALID_SOCKET)) //使用if判断是否创建成功 { printf("socket failed with error %d\n",WSAGetLastError);//使用WSAGetLastError得到错误信息 WSACleanup();//结束前清理 system("pause"); return; } ServerAddr.sin_family=AF_INET; ServerAddr.sin_port=htons(Port); ServerAddr.sin_addr.S_un.S_addr=htonl(INADDR_ANY); if((bind(ListeningSocket,(SOCKADDR*)&ServerAddr,sizeof(ServerAddr)))==SOCKET_ERROR) { printf("bind failed with error %d\n",WSAGetLastError()); closesocket(ListeningSocket); WSACleanup(); system("pause"); return; } if((listen(ListeningSocket,5))==SOCKET_ERROR) { printf("listen failed with error %d\n",WSAGetLastError()); closesocket(ListeningSocket); WSACleanup(); system("pause"); return; } printf("We are waiting a connection on port %d.\n",Port); printf("Listen(正在监听)...\n"); if((NewConnection=accept(ListeningSocket,(SOCKADDR*)&ClientAddr,&ClientAddrLen))==INVALID_SOCKET) //在此定义一个客户端的套接字,接收后会得到一个客户端的套接字 { printf("ACCEPT FAILED WITH ERROR %d\n",WSAGetLastError()); closesocket(ListeningSocket); WSACleanup(); system("pause"); return; } printf("We successfully got a connectiong from %s:%d\n",inet_ntoa(ClientAddr.sin_addr),ntohs(ClientAddr.sin_port)); if((Ret =recv(NewConnection,DataBuffer,sizeof(DataBuffer),0))==SOCKET_ERROR) { printf("recv failed with error %d\n",WSAGetLastError()); closesocket(NewConnection); WSACleanup(); system("pause"); return; } //此时已成功接收到客户端发送来的数据,将其显示出来 printf("We successfully received %d bytes.\n",Ret); DataBuffer[Ret]='\0';//结尾加上\0表示字符串结束 printf("%s\n",DataBuffer); printf("Ww are now going to close the client connectiong.\n"); closesocket(NewConnection); WSACleanup(); system("pause"); } ```
客户端断开服务端就会产生异常并断开
WIN10上开发一个服务端程序,它能监听来自多个客户端的请求并连接,其中客户端会往服务端传送文件,使用SOCKET tcp协议。现在是每次客户端发送完文件后,服务端也能正常接收完文件,但接收完后就会产生异常退出。是开的线程来运行接收函数,现在要怎样定位问题呢?exe直接退出要应该怎么抓取log呢? 接收部分代码如下: DWORD CClient::RecvDataThread(void* pParam) { CClient *pClient = (CClient*)pParam; //pointer to client int reVal; //return value char temp[MAX_NUM_BUF]; //temp value WriteToLog("RecvDataThread"); cout <<"RecvDataThread"<<endl; while(pClient->m_bConning) //connection status { // if(!pClient->m_bSendConnectionSuccess) // { // break; // } cout <<"pClient->m_bConning"<<endl; memset(temp, 0, MAX_NUM_BUF); reVal = recv(pClient->m_socket, temp, MAX_NUM_BUF, 0); //receive data //handle error return values if (SOCKET_ERROR == reVal) { int nErrCode = WSAGetLastError(); if ( WSAEWOULDBLOCK == nErrCode ) //receive data buffer is invalid { continue; //continue loop }else if (WSAENETDOWN == nErrCode ||//client close connection WSAETIMEDOUT == nErrCode || WSAECONNRESET == nErrCode ) { break; //thread exit } } //client close the connection if ( reVal == 0) { break; } //receive data if (reVal > 0) { cout <<"reVal > 0"<<endl; EnterCriticalSection(&pClient->m_cs); char *pClientIP = inet_ntoa(pClient->m_addr.sin_addr); u_short clientPort = ntohs(pClient->m_addr.sin_port); // cout<<"IP: "<<pClientIP<<"\tPort: "<<clientPort<<":"<<temp<<endl; //output and show data WriteToLog(temp); char file_name[MAX_NUM_BUF]; char *pfile = temp; // indicate path memset(file_name, 0, MAX_NUM_BUF); strncpy_s(file_name, "F:\\receive\\", strlen("F:\\receive\\")); int file_len = strlen(temp), i = 0, tem = 0; for (i = 0; i < file_len; i++) { if (strncmp(pfile + file_len - 1 -i, "\\", 1)) //if equal, return 0; else, return Positive { tem++; continue; //not equal } else // if equal, strcat path after \\ to file_name, it's exact length of path after { strncat_s(file_name, pfile + file_len - i, i); break; } } if (tem == file_len) { strncat_s(file_name, temp, strlen(temp) > 1024 ? 1024 : strlen(temp)); } FILE *fp; fopen_s(&fp, file_name, "wb"); int len = send(pClient->m_socket, "Ready to send", strlen("Ready to send") + 1, 0); memset(sendMsgLogA, 0, 1024); sprintf_s(sendMsgLogA, "%s%d", "send size: ", len ); WriteToLog(sendMsgLogA); char datalength[20]; long int length = 0; int lenRecv = recv(pClient->m_socket, datalength, 21, 0); //send file size from Client length = atol(datalength); memset(sendMsgLogA, 0, 1024); sprintf_s(sendMsgLogA, "%s%ld%s%ld", "file size: ", length, " recv size:", lenRecv); WriteToLog(sendMsgLogA); //ready to send double cent = 0.0; char receiveBuf[SIZE]; long int x = 0; while (1) { cout <<"while (1)"<<endl; x = x + SIZE; //SIZE scope is from -128 to 127 if (x < length) // ZJX { cent = (double)x*100.0 / (double)length; memset(sendMsgLogA, 0, 1024); sprintf_s(sendMsgLogA, "%s%4.2f", "have received: ", cent); WriteToLog(sendMsgLogA); //ready to send recv(pClient->m_socket, receiveBuf, SIZE + 1, 0); //recv SIZE files fwrite(receiveBuf, 1, SIZE, fp); //write SIZE files into receiveBuf, and continue to loop } else //excute the function directory while files is smaller, and loop exit { recv(pClient->m_socket, receiveBuf, length + SIZE - x + 1, 0); fwrite(receiveBuf, 1, length + SIZE - x, fp); fclose(fp); WriteToLog("file received done"); break; } } } WriteToLog("out of reVal>0"); LeaveCriticalSection(&pClient->m_cs); WriteToLog("out of LeaveCriticalSection"); memset(temp, 0, MAX_NUM_BUF); //clean up temp variables } WriteToLog("out of pClient->m_bConning"); pClient->m_bConning = FALSE; //disconnect with client return 0; //thread exit } ``` ```
libuv客户端开发,通过TCP/IP连接服务端出错!
使用libuv进行客户端开发,在Linux下测试没有问题,当移植到win7下面就报错了,错误信息如下: ![Valid XHTML](http://img.my.csdn.net/uploads/201311/21/1385026391_9075.jpg) 具体代码: ....... void uv_write_cb(uv_write_t *req,int status) { if(status == -1) { cout<<"error on_write_end"<<endl; return; } //cout<<"write_end!!!"<<endl; req->handle->data = req->data; uv_read_start(req->handle,alloc_buffer,uv_read_cb); //req->handle->loop->stop_flag = 1; } ...... void connect_server(uv_connect_t *req,int status) { ...... char buffer[100]; uv_buf_t buf = uv_buf_init(buffer,sizeof(buffer)); buf.len = strlen(fileName)+1; buf.base = fileName; uv_stream_t* tcp = req->handle; uv_write_t write_req; write_req.data = req->data; int buf_count = 1; uv_write(&write_req,tcp,&buf,buf_count,client::uv_write_cb); ...... } int _tmain(int argc, _TCHAR* argv[]) { ...... _loop = uv_default_loop(); uv_tcp_t socket; uv_tcp_init(_loop,&socket); uv_connect_t connect; connect.data = (void*)this; //struct sockaddr dest; struct sockaddr_in dest; uv_ip4_addr(_ipaddr.c_str(),_port,&dest); //struct sockaddr addrInfo; uv_tcp_connect(&connect,&socket,(const struct sockaddr*)&dest,connect_server); uv_run(_loop,UV_RUN_DEFAULT); return 0; ...... }
我想用java建立tcp/ip服务器然后用flash接受服务器发送的数据,同事将数据发送给js代码然后进一步操作
服务器代码: package JSocket; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class Server { private static final int PORT = 3000; // 端口号 private static List<Socket> list = new ArrayList<Socket>(); // 保存连接对象 private ExecutorService exec; private ServerSocket server; public static void main(String[] args) { new Server(); } public Server() { try { server = new ServerSocket(PORT); exec = Executors.newCachedThreadPool(); System.out.println("服务器已启动!"); Socket client = null; while (true) { client = server.accept(); // 接收客户连接 list.add(client); exec.execute(new ChatTask(client)); } } catch (IOException e) { e.printStackTrace(); } } static class ChatTask implements Runnable { private Socket socket; private BufferedReader br; private String msg=""; public ChatTask(Socket socket) throws IOException { this.socket = socket; br = new BufferedReader(new InputStreamReader(socket.getInputStream())); } public void run() { new Thread(new Runnable() { public void run() { PrintWriter pw; try { pw = new PrintWriter(socket.getOutputStream(), true); int i = 0; while(true){ i=i+1; msg=i+"\n"; try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } pw.println(msg); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }).start(); } } } 客户端代码: <?xml version="1.0" encoding="utf-8"?> <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600" applicationComplete="initApp()"> <fx:Script> <![CDATA[ import flash.net.Socket; import mx.controls.Alert; private var socket:Socket; private function initApp():void { StartTest(); } private function StartTest():void { socket = new Socket("127.0.0.1",3000); // socket.addEventListener(Event.CONNECT, connectHandler); socket.addEventListener(ProgressEvent.SOCKET_DATA, socketDataHandler); } private function CloseTest():void { if(socket!=null && socket.connected) { trace("socket.connected:"+socket.connected); socket.close(); trace("socket.connected:"+socket.connected); } } // private function connectHandler(event:Event):void // { // trace("connectHandler: " + event); // socket.writeMultiByte(SendStr.text,"GB2312"); // socket.flush(); // } private function socketDataHandler(event:ProgressEvent):void { trace("socketDataHandler: " + event); var str:String=socket.readMultiByte(socket.bytesAvailable,"GB2312"); [color=red]ExternalInterface.call("addValue",str);[/color] // Alert.show(str); // ReceiveStr.text = str; } private function alert():void{ for(var i:int=0;i<10;i++){ ExternalInterface.call("addValue","success!"+i); } } ]]> </fx:Script> <mx:TextArea id="ReceiveStr" x="53" y="68" width="200" height="200"/> <s:Button click="alert()" label="alert"/> </s:Application> jsp代码: <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>jsocketTest</title> <script type="text/javascript" src="<%=basePath%>jsocketTest/JSocket/jSocket.js"></script> </head> <body> [color=red]<script type='text/javascript'> function addValue(value) { alert(value); //mySocket.innerText = mySocket.innerText + value; } </script>[/color] <div id='mySocket' /></div> <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="100%" height="100%" id="SocketTest"> <param name="movie" value="bin-debug/SocketTest.swf" /> <param name="quality" value="high" /> <param name="bgcolor" value="#ffffff" /> <param name="allowScriptAccess" value="sameDomain" /> <param name="allowFullScreen" value="true" /> <!--[if !IE]>--> <object type="application/x-shockwave-flash" data="bin-debug/SocketTest.swf" width="100%" height="100%"> <param name="quality" value="high" /> <param name="bgcolor" value="#ffffff" /> <param name="allowScriptAccess" value="sameDomain" /> <param name="allowFullScreen" value="true" /> <!--<![endif]--> <!--[if gte IE 6]>--> <p> Either scripts and active content are not permitted to run or Adobe Flash Player version 10.0.0 or greater is not installed. </p> <!--<![endif]--> <a href="http://www.adobe.com/go/getflashplayer"> <img src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash Player" /> </a> <!--[if !IE]>--> </object> <!--<![endif]--> </object> </body> </html> 我想用java建立tcp/ip服务器然后用flash接受服务器发送的数据,同事将数据发送给js代码然后进一步操作,但是flash单独运行可以接受到服务器的数据,但一旦传给js,js确接不到数据。正常用flash调用js函数还好使,就是flash从服务器接受到的数据在传给js就是显示不出来!帮帮我吧!先谢谢大家了!
Java网络编程输出有问题
客户端代码 import java.io.*; import java.net.Socket; /** * Created by apple on 17-6-7. * 多线程版本 * 让程序能够支持客户端一边输入一边接收来自服务端的消息 */ public class TCPClient2 { //testClient public static void main(String[] args){ Client sparkClient = new Client("Spark", "127.0.0.1", 8888); } } ​ class Client{ private static int totalNum = 0; //记录连接的客户端总数量 private Socket clientSock; private String userName; //客户端用户名 private final int ID = ++totalNum; //标识客户端唯一的号码,类似QQ号,且一经注册变不可改变 private BufferedReader clientReader; //客户端读入流 private BufferedReader userInputReader; private PrintWriter clientWriter; //客户端向服务端的输出流 private String clientInput; //客户端读入的数据,即从服务端传来的数据 private String userInput; private Thread inputThread = new Thread(new ClientRead()); //监控输入的线程 private Thread outputThread = new Thread(new ClientWrite()); //监控输出的线程 /*public Client(String userName, Socket sock){ //this(userName, (String)sock.getInetAddress(), sock.getPort()); //?????????? clientSock = sock; }*/ public Client(String userName, String ipAddress, int port){ try{ //id = ++totalNum; clientSock = new Socket(ipAddress, port); this.userName = userName; clientReader = new BufferedReader(new InputStreamReader(clientSock.getInputStream())); clientWriter = new PrintWriter(clientSock.getOutputStream(), true); userInputReader = new BufferedReader(new InputStreamReader(System.in)); inputThread.start(); outputThread.start(); System.out.println("Connected, just enjoy the communication!"); } catch (IOException e){ e.printStackTrace(); System.exit(-1); } } public Client(){ this("Durant", "127.0.0.1", 8888); //this((Socket) ("Spark","127.0.0.1", 8888)); } //尝试随机产生类似QQ号的号码,用户名可以重复 protected void finalize(){close();} //getter public Socket getSocket(){ return clientSock; } public int getID (){return ID;} public String getUserName(){return userName;} //public String getClientInput(){return clientInput;} //public BufferedReader getClientReader(){return clientReader;} //public PrintWriter getClientOutput(){return clientWriter;} public String getUserInput(){ //客户端接受用户的输入作为写入服务端的信息 //inputHint(); try{ userInput = userInputReader.readLine(); }catch (IOException e){ e.printStackTrace(); System.exit(-1); } return userInput; } //setter public void setSocket(Socket sock){ clientSock = sock; } public void setUserName(String userName){this.userName = userName;} //从客户端读入来自服务端或用户写入的数据 public String read(){ try { clientInput = clientReader.readLine(); //将服务端写入的数据读入进来 }catch (IOException e){ e.printStackTrace(); System.exit(-1); } return clientInput; } //从客户端写入数据到服务端 public void write(){ getUserInput(); clientWriter.println(userInput); clientWriter.flush(); // clientOutput.flush(); } //将服务端传来的消息打印出来 public void printServerMessage(){ System.out.println("Server:" + clientInput); } public void printClientMessage(){ System.out.println("Client:" + userInput); } public void printServerDisconnected() { System.out.println("Sorry, the server is disconnected!"); } public void printClientDisconnected() { clientWriter.println("User#" + ID + ", " + userName + "is disconnected!"); } public void close(){ try{ clientSock.close(); clientReader.close(); userInputReader.close(); clientWriter.close(); }catch (IOException e){ e.printStackTrace(); System.exit(-1); } } //判断服务器是否仍在连接中 public boolean serverIsConnected(){ return !clientInput.equals("bye"); } public boolean clientIsConnected(){ return !getUserInput().equals("bye"); } //实现线程的方法————时刻准备接收来自服务端的消息 public class ClientRead implements Runnable { public void run() { read(); while (clientReader != null && serverIsConnected() && clientInput.length()!=0) { printServerMessage(); read(); } printServerDisconnected(); } } //实现线程的方法————时刻准备向服务端发送消息 class ClientWrite implements Runnable{ public void run() { write(); while (userInputReader != null && clientIsConnected() && userInput.length()!=0){ //printClientMessage(); write(); } printClientDisconnected(); } } } 服务端代码: import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; /** * Created by apple on 17-6-7. * 多线程版本 * 让程序能够支持客户端一边输入一边接收来自服务端的消息 */ public class TCPServer { public static void main(String[] args){ Server sparkServer = new Server("Curry", 8888); } } class Server{ private ServerSocket serverSock; private Socket clientSock; private String serverName; //服务端名 private BufferedReader serverReader; //服务端读入流 private BufferedReader userInputReader; private PrintWriter serverWriter; //服务端向客户端的输出流 private String serverInput; //服务端读入的数据,即从客户端传来的数据 private String userInput; private Thread inputThread = new Thread(new ServerRead()); //监控输入的线程 private Thread outputThread = new Thread(new ServerWrite()); //监控输出的线程 public Server(String serverName, int port){ try{ this.serverName = serverName; serverSock = new ServerSocket(port); clientSock = serverSock.accept(); serverReader = new BufferedReader(new InputStreamReader(clientSock.getInputStream())); userInputReader = new BufferedReader(new InputStreamReader(System.in)); serverWriter = new PrintWriter(clientSock.getOutputStream(), true); inputThread.start(); outputThread.start(); }catch (IOException e){ e.printStackTrace(); System.exit(-1); } } public Server(){ this("SuperQQ", 8888); } protected void finalize(){close();} //getter public ServerSocket getServerSocket(){ return serverSock; } public String getServerName(){return serverName;} public String getUserInput(){ try{ userInput = userInputReader.readLine(); }catch (IOException e){ e.printStackTrace(); System.exit(-1); } return userInput; } //setter public void setServerSocket(ServerSocket serverSock){ this.serverSock = serverSock; } public void setServerSocket(int port){ try{ serverSock = new ServerSocket(port); }catch (IOException e){ e.printStackTrace(); System.exit(-1); } } //接收客户端以及用户在控制台的输入传入服务端 public String read(){ try { serverInput = serverReader.readLine(); //将客户端写入的数据读入进来 }catch (IOException e){ e.printStackTrace(); System.exit(-1); } return serverInput; } //从服务端写入数据到客户端 public void write(){ getUserInput(); serverWriter.println(userInput); serverWriter.flush(); } //将客户端传来的消息打印出来 public void printClientMessage(){ System.out.println("Client:" + serverInput); } //将服务端写的消息打印出来 public void printServerMessage() { System.out.println("Server:" + userInput); } public void close(){ try { serverWriter.close(); userInputReader.close(); serverReader.close(); serverSock.close(); }catch (IOException e){ e.printStackTrace(); System.exit(-1); } } //判断服务器是否仍在连接中 public boolean serverIsConnected(){ return !serverInput.equals("bye"); } public boolean clientIsConnected(){ return !getUserInput().equals("bye"); } //实现线程的方法————时刻准备接收来自客户端的消息 public class ServerRead implements Runnable { public void run() { read(); while (serverReader != null && serverIsConnected() && serverInput.length()!=0) { printClientMessage(); read(); } //printServerDisconnected(); } } //实现线程的方法————时刻准备向服务端发送消息 class ServerWrite implements Runnable{ public void run() { write(); while (userInputReader != null && clientIsConnected() && userInput.length()!=0){ //printServerMessage(); write(); } //printClientDisconnected(); } } }
shutdown关闭读这一半后为什么还能收到对端的数据。
之前看unix网络编程,shutdown函数读半关闭会丢弃数据的,但是我写了个测试程序,在同一个主机上运行,关闭读这一半后还是可以读到数据,这是为什么? client ``` #include <stdio.h> #include <sys/socket.h> #include <errno.h> #include <string.h> #include <sys/types.h> #include <netinet/in.h> int main(int argc,char ** argv) { int fd; struct sockaddr_in addr; int ret; int i; char buf[256] = {0}; fd = socket(AF_INET,SOCK_STREAM,0); if(fd < 0){ fprintf(stderr,"socket error\n"); return -1; } addr.sin_family = AF_INET; addr.sin_port = htons(8888); addr.sin_addr.s_addr = inet_addr("127.0.0.1"); ret = connect(fd,(struct sockaddr*)&addr,sizeof(addr)); if(ret < 0){ fprintf(stderr,"connect error:%s\n",strerror(errno)); close(fd); return -1; } i = 0; while(1){ #if 1 if(i == 5){ printf("shutdown read\n"); shutdown(fd,SHUT_RD); } #endif if(i == 10){ printf("client break\n"); shutdown(fd,SHUT_WR); break; } write(fd,"1234567890",10); i++; memset(buf,0,sizeof(buf)); if((ret = read(fd,buf,sizeof(buf))) >0){ printf("ret=%d,buf:%s\n",ret,buf); } sleep(1); } sleep(2); close(fd); return 0; } ``` server ``` void recive_data(void *p) { int fd = *((int *)p); char buf[256] = {0}; char out_data[256] = {0}; int status = 0; int ret; int i = 0; while(1){ memset(buf,0,sizeof(buf)); if((ret = read(fd,buf,sizeof(buf)))>0){ printf("server buf:%s\n"); } else{ printf("ret=%d,recv fin\n",ret); break; } i++; sprintf(out_data,"the %d tims,0987654321\n",i); ret = write(fd,out_data,strlen(out_data)); if(ret > 0){ printf("server write %d bytes data to client\n",ret); } } close(fd); //pthread_exit((void *)&status); return 0; } int main(int argc,char **argv) { int socketfd = -1; struct sockaddr_in addr; struct sockaddr addr_client; int addr_len; int ret; int listenfd = -1; fd_set rdset; pthread_t tid; int status; socketfd = socket(AF_INET,SOCK_STREAM,0); if(socketfd < 0){ fprintf(stderr,"socket error:%s \n",strerror(errno)); return -1; } addr.sin_family = AF_INET; addr.sin_port = htons(8888); addr.sin_addr.s_addr = htonl(INADDR_ANY); ret =bind(socketfd,(struct sockaddr*)&addr,sizeof(addr)); if(ret < 0){ fprintf(stderr,"bind error:%s\n",strerror(errno)); return -1; } listen(socketfd,0); while(1){ listenfd = accept(socketfd,&addr_client,&addr_len); if(listenfd < 0){ fprintf(stderr,"accept error:%s\n",strerror(errno)); return -1; } printf("listenfd=%d\n",listenfd); if(pthread_create(&tid,NULL,recive_data,(void *)&listenfd)<0){ fprintf(stderr,"pthread_create error:%s\n",strerror(errno)); return -1; } //pthread_join(tid,&status); } close(socketfd); } ``` 运行结果如下 shishaowei@T330A:~/test/IPC/socket/tcp$ ./tcp_server & [1] 8567 shishaowei@T330A:~/test/IPC/socket/tcp$ ./tcp_client listenfd=4 server buf:1234567890 server write 22 bytes data to client ret=22,buf:the 1 tims,0987654321 server buf:1234567890 server write 22 bytes data to client ret=22,buf:the 2 tims,0987654321 server buf:1234567890 server write 22 bytes data to client ret=22,buf:the 3 tims,0987654321 server buf:1234567890 server write 22 bytes data to client ret=22,buf:the 4 tims,0987654321 server buf:1234567890 server write 22 bytes data to client ret=22,buf:the 5 tims,0987654321 shutdown read server buf:1234567890 server write 22 bytes data to client ret=22,buf:the 6 tims,0987654321 server buf:1234567890 server write 22 bytes data to client ret=22,buf:the 7 tims,0987654321 server buf:1234567890 server write 22 bytes data to client ret=22,buf:the 8 tims,0987654321 server buf:1234567890 server write 22 bytes data to client ret=22,buf:the 9 tims,0987654321 server buf:1234567890 server write 23 bytes data to client client break ret=0,recv fin
C++服务端发送给客户端消息,但客户端没有显示
服务端代码: #include"iostream" #include<winsock2.h> #pragma comment(lib,"ws2_32") #include<stdlib.h> using namespace std; int main() { WSADATA wsaData; WSAStartup(MAKEWORD(2, 2), &wsaData); SOCKET s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); sockaddr_in sockaddr; sockaddr.sin_family = PF_INET; sockaddr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1"); sockaddr.sin_port = htons(827); bind(s, (SOCKADDR*)&sockaddr, sizeof(SOCKADDR)); listen(s, 1); SOCKADDR clientAddr; int nSize = sizeof(SOCKADDR); SOCKET clientSock; clientSock = accept(s, (SOCKADDR*)&clientAddr, &nSize); send(clientSock, "helllo client \r\n", strlen("hello client \r\n") + sizeof(char), NULL); closesocket(clientSock); closesocket(s); WSACleanup(); return 0; } 客户端代码: #include"iostream" #include<stdlib.h> #include<winsock2.h> #pragma comment(lib,"ws2_32") using namespace std; int main() { WSADATA wsaData; WSAStartup(MAKEWORD(2, 2), &wsaData); SOCKET s = socket(PF_INET,SOCK_STREAM, IPPROTO_TCP); sockaddr_in sockAddr; sockAddr.sin_family = PF_INET; sockAddr.sin_addr.S_un.S_addr = inet_addr("127,0,0,1"); sockAddr.sin_port = htons(827); connect(s, (SOCKADDR*)&sockAddr, sizeof(SOCKADDR)); char szBuffer[MAXBYTE] = { 0 }; recv(s, szBuffer, MAXBYTE, NULL); printf("szBuffer=%s\r\n", szBuffer); closesocket(s); WSACleanup(); return 0; }
在中国程序员是青春饭吗?
今年,我也32了 ,为了不给大家误导,咨询了猎头、圈内好友,以及年过35岁的几位老程序员……舍了老脸去揭人家伤疤……希望能给大家以帮助,记得帮我点赞哦。 目录: 你以为的人生 一次又一次的伤害 猎头界的真相 如何应对互联网行业的「中年危机」 一、你以为的人生 刚入行时,拿着傲人的工资,想着好好干,以为我们的人生是这样的: 等真到了那一天,你会发现,你的人生很可能是这样的: ...
【JSON解析】浅谈JSONObject的使用
简介 在程序开发过程中,在参数传递,函数返回值等方面,越来越多的使用JSON。JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,同时也易于机器解析和生成、易于理解、阅读和撰写,而且Json采用完全独立于语言的文本格式,这使得Json成为理想的数据交换语言。 JSON建构于两种结构: “名称/值”对的集合(A Collection of name/va...
《MySQL 性能优化》之理解 MySQL 体系结构
本文介绍 MySQL 的体系结构,包括物理结构、逻辑结构以及插件式存储引擎。
程序员请照顾好自己,周末病魔差点一套带走我。
程序员在一个周末的时间,得了重病,差点当场去世,还好及时挽救回来了。
一名大专同学的四个问题
【前言】   收到一封来信,赶上各种事情拖了几日,利用今天要放下工作的时机,做个回复。   2020年到了,就以这一封信,作为开年标志吧。 【正文】   您好,我是一名现在有很多困惑的大二学生。有一些问题想要向您请教。   先说一下我的基本情况,高考失利,不想复读,来到广州一所大专读计算机应用技术专业。学校是偏艺术类的,计算机专业没有实验室更不用说工作室了。而且学校的学风也不好。但我很想在计算机领...
复习一周,京东+百度一面,不小心都拿了Offer
京东和百度一面都问了啥,面试官百般刁难,可惜我全会。
Java 14 都快来了,为什么还有这么多人固守Java 8?
从Java 9开始,Java版本的发布就让人眼花缭乱了。每隔6个月,都会冒出一个新版本出来,Java 10 , Java 11, Java 12, Java 13, 到2020年3月份,...
达摩院十大科技趋势发布:2020 非同小可!
【CSDN编者按】1月2日,阿里巴巴发布《达摩院2020十大科技趋势》,十大科技趋势分别是:人工智能从感知智能向认知智能演进;计算存储一体化突破AI算力瓶颈;工业互联网的超融合;机器间大规模协作成为可能;模块化降低芯片设计门槛;规模化生产级区块链应用将走入大众;量子计算进入攻坚期;新材料推动半导体器件革新;保护数据隐私的AI技术将加速落地;云成为IT技术创新的中心 。 新的画卷,正在徐徐展开。...
轻松搭建基于 SpringBoot + Vue 的 Web 商城应用
首先介绍下在本文出现的几个比较重要的概念: 函数计算(Function Compute): 函数计算是一个事件驱动的服务,通过函数计算,用户无需管理服务器等运行情况,只需编写代码并上传。函数计算准备计算资源,并以弹性伸缩的方式运行用户代码,而用户只需根据实际代码运行所消耗的资源进行付费。Fun: Fun 是一个用于支持 Serverless 应用部署的工具,能帮助您便捷地管理函数计算、API ...
讲真,这两个IDE插件,可以让你写出质量杠杠的代码
周末躺在床上看《拯救大兵瑞恩》 周末在闲逛的时候,发现了两个优秀的 IDE 插件,据说可以提高代码的质量,我就安装了一下,试了试以后发现,确实很不错,就推荐给大家。 01、Alibaba Java 代码规范插件 《阿里巴巴 Java 开发手册》,相信大家都不会感到陌生,其 IDEA 插件的下载次数据说达到了 80 万次,我今天又贡献了一次。嘿嘿。 该项目的插件地址: https://github....
Python+OpenCV实时图像处理
目录 1、导入库文件 2、设计GUI 3、调用摄像头 4、实时图像处理 4.1、阈值二值化 4.2、边缘检测 4.3、轮廓检测 4.4、高斯滤波 4.5、色彩转换 4.6、调节对比度 5、退出系统 初学OpenCV图像处理的小伙伴肯定对什么高斯函数、滤波处理、阈值二值化等特性非常头疼,这里给各位分享一个小项目,可通过摄像头实时动态查看各类图像处理的特点,也可对各位调参、测试...
2020年一线城市程序员工资大调查
人才需求 一线城市共发布岗位38115个,招聘120827人。 其中 beijing 22805 guangzhou 25081 shanghai 39614 shenzhen 33327 工资分布 2020年中国一线城市程序员的平均工资为16285元,工资中位数为14583元,其中95%的人的工资位于5000到20000元之间。 和往年数据比较: yea...
为什么猝死的都是程序员,基本上不见产品经理猝死呢?
相信大家时不时听到程序员猝死的消息,但是基本上听不到产品经理猝死的消息,这是为什么呢? 我们先百度搜一下:程序员猝死,出现将近700多万条搜索结果: 搜索一下:产品经理猝死,只有400万条的搜索结果,从搜索结果数量上来看,程序员猝死的搜索结果就比产品经理猝死的搜索结果高了一倍,而且从下图可以看到,首页里面的五条搜索结果,其实只有两条才是符合条件。 所以程序员猝死的概率真的比产品经理大,并不是错...
害怕面试被问HashMap?这一篇就搞定了!
声明:本文以jdk1.8为主! 搞定HashMap 作为一个Java从业者,面试的时候肯定会被问到过HashMap,因为对于HashMap来说,可以说是Java集合中的精髓了,如果你觉得自己对它掌握的还不够好,我想今天这篇文章会非常适合你,至少,看了今天这篇文章,以后不怕面试被问HashMap了 其实在我学习HashMap的过程中,我个人觉得HashMap还是挺复杂的,如果真的想把它搞得明明白...
毕业5年,我问遍了身边的大佬,总结了他们的学习方法
我问了身边10个大佬,总结了他们的学习方法,原来成功都是有迹可循的。
python爬取百部电影数据,我分析出了一个残酷的真相
2019年就这么匆匆过去了,就在前几天国家电影局发布了2019年中国电影市场数据,数据显示去年总票房为642.66亿元,同比增长5.4%;国产电影总票房411.75亿元,同比增长8.65%,市场占比 64.07%;城市院线观影人次17.27亿,同比增长0.64%。 看上去似乎是一片大好对不对?不过作为一名严谨求实的数据分析师,我从官方数据中看出了一点端倪:国产票房增幅都已经高达8.65%了,为什...
推荐10个堪称神器的学习网站
每天都会收到很多读者的私信,问我:“二哥,有什么推荐的学习网站吗?最近很浮躁,手头的一些网站都看烦了,想看看二哥这里有什么新鲜货。” 今天一早做了个恶梦,梦到被老板辞退了。虽然说在我们公司,只有我辞退老板的份,没有老板辞退我这一说,但是还是被吓得 4 点多都起来了。(主要是因为我掌握着公司所有的核心源码,哈哈哈) 既然 4 点多起来,就得好好利用起来。于是我就挑选了 10 个堪称神器的学习网站,推...
这些软件太强了,Windows必装!尤其程序员!
Windows可谓是大多数人的生产力工具,集娱乐办公于一体,虽然在程序员这个群体中都说苹果是信仰,但是大部分不都是从Windows过来的,而且现在依然有很多的程序员用Windows。 所以,今天我就把我私藏的Windows必装的软件分享给大家,如果有一个你没有用过甚至没有听过,那你就赚了????,这可都是提升你幸福感的高效率生产力工具哦! 走起!???? NO、1 ScreenToGif 屏幕,摄像头和白板...
阿里面试,面试官没想到一个ArrayList,我都能跟他扯半小时
我是真的没想到,面试官会这样问我ArrayList。
曾经优秀的人,怎么就突然不优秀了。
职场上有很多辛酸事,很多合伙人出局的故事,很多技术骨干被裁员的故事。说来模板都类似,曾经是名校毕业,曾经是优秀员工,曾经被领导表扬,曾经业绩突出,然而突然有一天,因为种种原因,被裁员了,...
大学四年因为知道了这32个网站,我成了别人眼中的大神!
依稀记得,毕业那天,我们导员发给我毕业证的时候对我说“你可是咱们系的风云人物啊”,哎呀,别提当时多开心啦????,嗯,我们导员是所有导员中最帅的一个,真的???? 不过,导员说的是实话,很多人都叫我大神的,为啥,因为我知道这32个网站啊,你说强不强????,这次是绝对的干货,看好啦,走起来! PS:每个网站都是学计算机混互联网必须知道的,真的牛杯,我就不过多介绍了,大家自行探索,觉得没用的,尽管留言吐槽吧???? 社...
良心推荐,我珍藏的一些Chrome插件
上次搬家的时候,发了一个朋友圈,附带的照片中不小心暴露了自己的 Chrome 浏览器插件之多,于是就有小伙伴评论说分享一下我觉得还不错的浏览器插件。 我下面就把我日常工作和学习中经常用到的一些 Chrome 浏览器插件分享给大家,随便一个都能提高你的“生活品质”和工作效率。 Markdown Here Markdown Here 可以让你更愉快的写邮件,由于支持 Markdown 直接转电子邮...
看完这篇HTTP,跟面试官扯皮就没问题了
我是一名程序员,我的主要编程语言是 Java,我更是一名 Web 开发人员,所以我必须要了解 HTTP,所以本篇文章就来带你从 HTTP 入门到进阶,看完让你有一种恍然大悟、醍醐灌顶的感觉。 最初在有网络之前,我们的电脑都是单机的,单机系统是孤立的,我还记得 05 年前那会儿家里有个电脑,想打电脑游戏还得两个人在一个电脑上玩儿,及其不方便。我就想为什么家里人不让上网,我的同学 xxx 家里有网,每...
史上最全的IDEA快捷键总结
现在Idea成了主流开发工具,这篇博客对其使用的快捷键做了总结,希望对大家的开发工作有所帮助。
阿里程序员写了一个新手都写不出的低级bug,被骂惨了。
这种新手都不会范的错,居然被一个工作好几年的小伙子写出来,差点被当场开除了。
谁是华为扫地僧?
是的,华为也有扫地僧!2020年2月11-12日,“养在深闺人不知”的华为2012实验室扫地僧们,将在华为开发者大会2020(Cloud)上,和大家见面。到时,你可以和扫地僧们,吃一个洋...
AI 没让人类失业,搞 AI 的人先失业了
最近和几个 AI 领域的大佬闲聊 根据他们讲的消息和段子 改编出下面这个故事 如有雷同 都是巧合 1. 老王创业失败,被限制高消费 “这里写我跑路的消息实在太夸张了。” 王葱葱哼笑一下,把消息分享给群里。 阿杰也看了消息,笑了笑。在座几位也都笑了。 王葱葱是个有名的人物,21岁那年以全额奖学金进入 KMU 攻读人工智能博士,累计发表论文 40 余篇,个人技术博客更是成为深度学习领域内风向标。 ...
2020年,冯唐49岁:我给20、30岁IT职场年轻人的建议
点击“技术领导力”关注∆每天早上8:30推送 作者|Mr.K 编辑| Emma 来源|技术领导力(ID:jishulingdaoli) 前天的推文《冯唐:职场人35岁以后,方法论比经验重要》,收到了不少读者的反馈,觉得挺受启发。其实,冯唐写了不少关于职场方面的文章,都挺不错的。可惜大家只记住了“春风十里不如你”、“如何避免成为油腻腻的中年人”等不那么正经的文章。 本文整理了冯...
作为一名大学生,如何在B站上快乐的学习?
B站是个宝,谁用谁知道???? 作为一名大学生,你必须掌握的一项能力就是自学能力,很多看起来很牛X的人,你可以了解下,人家私底下一定是花大量的时间自学的,你可能会说,我也想学习啊,可是嘞,该学习啥嘞,不怕告诉你,互联网时代,最不缺的就是学习资源,最宝贵的是啥? 你可能会说是时间,不,不是时间,而是你的注意力,懂了吧! 那么,你说学习资源多,我咋不知道,那今天我就告诉你一个你必须知道的学习的地方,人称...
立即提问