标签:route 全面 date exp eof bytes bridge uga 重启
package com.socket; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.Writer; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; import java.net.SocketTimeoutException; import java.text.SimpleDateFormat; import java.util.Date; public class SocketServer { public static String _pattern = "yyyy-MM-dd HH:mm:ss SSS"; public static SimpleDateFormat format = new SimpleDateFormat(_pattern); // 设置超时间 public static int _sec = 0; public static void main(String[] args) { System.out.println("----------Server----------"); System.out.println(format.format(new Date())); ServerSocket server; try { server = new ServerSocket(8001); System.out.println("监听建立 等你上线\n"); Socket socket = server.accept(); System.out.println(format.format(new Date())); System.out.println("建立了链接\n"); BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream())); socket.setSoTimeout(_sec * 1000); System.out.println(format.format(new Date()) + "\n" + _sec + "秒的时间 快写\n"); System.out.println(format.format(new Date()) + "\nClient:" + br.readLine() + "\n"); Writer writer = new OutputStreamWriter(socket.getOutputStream()); System.out.println(format.format(new Date())); System.out.println("我在写回复\n"); writer.write("收到\n"); Thread.sleep(10000); writer.flush(); System.out.println(format.format(new Date())); System.out.println("写完啦 你收下\n\n\n\n\n"); } catch (SocketTimeoutException e) { System.out.println(format.format(new Date()) + "\n" + _sec + "秒没给我数据 我下啦\n\n\n\n\n"); e.printStackTrace(); } catch (SocketException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } }
package com.socket.v3; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.Writer; import java.net.Socket; import java.net.SocketException; import java.net.SocketTimeoutException; import java.text.SimpleDateFormat; import java.util.Date; public class SocketClient { public static String _pattern = "yyyy-MM-dd HH:mm:ss SSS"; public static SimpleDateFormat format = new SimpleDateFormat(_pattern); // 设置超时间 public static int _sec = 5; public static void main(String[] args) { System.out.println("----------Client----------"); Socket socket = null; try { // 与服务端建立连接 socket = new Socket("127.0.0.1", 8001); socket.setSoTimeout(_sec * 1000); System.out.println(format.format(new Date())); System.out.println("建立了链接\n"); // 往服务写数据 Writer writer = new OutputStreamWriter(socket.getOutputStream()); System.out.println(format.format(new Date())); System.out.println("我在写啦\n"); Thread.sleep(10000); writer.write("有没有收到\n"); System.out.println(format.format(new Date())); System.out.println("写完啦 你收下\n"); writer.flush(); BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream())); System.out.println(format.format(new Date()) + "\n" + _sec + "秒的时间 告诉我你收到了吗\n"); System.out.println(format.format(new Date()) + "\nServer:" + br.readLine()); } catch (SocketTimeoutException e) { System.out.println(format.format(new Date()) + "\n" + _sec + "秒没收到回复 我下啦\n\n\n\n\n"); e.printStackTrace(); } catch (SocketException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } }
#include<winsock2.h> #include<stdio.h> #pragma comment(lib,"ws2_32.lib") void main() { WSADATA wsaData; SOCKET sockServer; SOCKADDR_IN addrServer; SOCKET sockClient; SOCKADDR_IN addrClient; WSAStartup(MAKEWORD(2,2),&wsaData); sockServer=socket(AF_INET,SOCK_STREAM,0); addrServer.sin_addr.S_un.S_addr=htonl(INADDR_ANY);//INADDR_ANY表示任何IP addrServer.sin_family=AF_INET; addrServer.sin_port=htons(6000);//绑定端口6000 bind(sockServer,(SOCKADDR*)&addrServer,sizeof(SOCKADDR)); //Listen监听端 listen(sockServer,5);//5为等待连接数目 printf("服务器已启动:\n监听中...\n"); int len=sizeof(SOCKADDR); char sendBuf[100];//发送至客户端的字符串 char recvBuf[100];//接受客户端返回的字符串 //会阻塞进程,直到有客户端连接上来为止 sockClient=accept(sockServer,(SOCKADDR*)&addrClient,&len); //接收并打印客户端数据 recv(sockClient,recvBuf,100,0); printf("%s\n",recvBuf); //关闭socket closesocket(sockClient); WSACleanup();}
#include<winsock2.h> #include<stdio.h> #pragma comment(lib,"ws2_32.lib") void main() { WSADATA wsaData; SOCKET sockClient;//客户端Socket SOCKADDR_IN addrServer;//服务端地址 WSAStartup(MAKEWORD(2,2),&wsaData); //新建客户端socket sockClient=socket(AF_INET,SOCK_STREAM,0); //定义要连接的服务端地址 addrServer.sin_addr.S_un.S_addr=inet_addr("127.0.0.1");//目标IP(127.0.0.1是回送地址) addrServer.sin_family=AF_INET; addrServer.sin_port=htons(6000);//连接端口6000 //连接到服务端 connect(sockClient,(SOCKADDR*)&addrServer,sizeof(SOCKADDR)); //发送数据 char message[20]="HelloSocket!"; send(sockClient,message,strlen(message)+1,0); //关闭socket closesocket(sockClient); WSACleanup();}
开启一个socket监听示例程序: <?php//设置一些基本的变量 $host="192.168.1.99";//主机地址 $port=1234;//端口 //设置超时时间 set_time_limit(0); //创建一个Socket $socket=socket_create(AF_INET,SOCK_STREAM,0)ordie("Couldnotcreatesocket\n");//绑定Socket到端口 $result=socket_bind($socket,$host,$port)ordie("Couldnotbindtosocket\n");//开始监听链接 $result=socket_listen($socket,3)ordie("Couldnotsetupsocketlistener\n");//acceptincomingconnections //另一个Socket来处理通信 $spawn=socket_accept($socket)ordie("Couldnotacceptincomingconnection\n");//获得客户端的输入 $input=socket_read($spawn,1024)ordie("Couldnotreadinput\n");//清空输入字符串 $input=trim($input);//处理客户端输入并返回结果 $output=strrev($input)."\n"; socket_write($spawn,$output,strlen($output))ordie("Couldnotwriteoutput\n");//关闭 socket_close($spawn); socket_close($socket);
public class XmlSocket { //异步socket侦听从客户端传来的数据 public static string data=null; //Threadsignal.线程用一个指示是否将初始状态设置为终止的布尔值初始化ManualResetEvent类的新实例。 public static ManualResetEvent allDone=new ManualResetEvent(false); static void Main(string[]args) { StartListening(); } public static void StartListening() { //传入数据缓冲 byte[] bytes = new Byte[1024]; //建立本地端口 IPAddress ipAddress; String ipString = ConfigurationManager.AppSettings.Get("SocketIP"); if(ipString == null || ipString == String.Empty) { IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName()); ipAddress = ipHostInfo.AddressList[0]; } else { ipAddress = IPAddress.Parse(ipString); } int port; String portString = ConfigurationManager.AppSettings.Get("SocketPort"); if(portString == null || portString == String.Empty) { port=11001; } else { port=int.Parse(portString); } IPEndPoint localEndPoint = new IPEndPoint(ipAddress, port); Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //绑定端口和数据 listener.Bind(localEndPoint); listener.Listen(100); while(true) {//设置无信号状态的事件 allDone.Reset(); //重启异步连接 listener.BeginAccept(new AsyncCallback(AcceptCallback),listener); //等待连接创建后继续 allDone.WaitOne(); } public static void AcceptCallback(IAsyncResult ar) { //接受回调方法。该方法的此节向主应用程序线程发出信号,让它继续处理并建立与客户端的连接 allDone.Set(); //获取客户端请求句柄 Socket listener = (Socket)ar.AsyncState; Socket handler = listener.EndAccept(ar); StateObject state = new StateObject(); state.workSocket = handler; handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback),state); } //与接受回调方法一样,读取回调方法也是一个AsyncCallback委托。该方法将来自客户端套接字的一个或多个字节读入数据缓冲区,然后再次调用BeginReceive方法,直到客户端发送的数据完成为止。从客户端读取整个消息后,在控制台上显示字符串,并关闭处理与客户端的连接的服务器套接字。 public static void ReadCallback(IAsyncResult ar) { String content = String.Empty; //创建自定义的状态对象 StateObject state = (StateObject)ar.AsyncState; Socket handler = state.workSocket;//处理的句柄 //读出 int bytesRead = handler.EndReceive(ar); if(bytesRead>0) { String len = Encoding.UTF8.GetBytes(result).Length.ToString().PadLeft(8,‘0‘); log.writeLine(len); Send(len + result, handler); } } private static void Send(string data, Socket handler) { byte[] byteData = Encoding.UTF8.GetBytes(data); handler.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), handler); } private static void SendCallback(IAsyncResult ar) { Socket handler = (Socket)ar.AsyncState; //向远端发送数据 int bytesSent = handler.EndSend(ar); StateObject state = new StateObject(); state.workSocket = handler; handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback),state); handler.Shutdown(SocketShutdown.Both); handler.Close(); } public static void StopListening() { allDone.Close(); log.close(); }
标签:route 全面 date exp eof bytes bridge uga 重启
原文地址:https://www.cnblogs.com/clj-boke123/p/10057642.html