socket用途:
网络聊天软件,如QQ就是用socket通信的。
浏览器和服务器也是socket通信的,只是传输的是以http协议的http报文。
Java Socket 侦听服务器上的连接:
/*
*来 自
NowJava.com - 时代Java
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class Main {
static Socket socket = null;
static PrintWriter out;
static BufferedReader in;
public static void main(String[] args) {
try {
socket = new Socket("127.0.0.1", 1234);/* from nowjava.com - 时代Java*/
// Obtain a handle on the socket output
out = new PrintWriter(socket.getOutputStream(), true);
// Obtain a handle on the socket input
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
testConnection();
System.out.println("Closing the connection...");
out.close();
in.close();
socket.close();
System.exit(1);
} catch (Exception e) {
System.out.println(e);
System.exit(1);
}
}
public static void testConnection() {
String serverResponse = null;
if (socket != null && in != null && out != null) {
System.out.println("Successfully connected, now testing...");
try {
// Send data to server
out.println("Here is a test.");
// Receive data from server
while ((serverResponse = in.readLine()) != null)
System.out.println(serverResponse);
} catch (IOException e) {
System.out.println(e);
System.exit(1);
}
}
}
}
socket 网络和套接字更多教程:
侦听服务器上的连接从带有套接字的服务器读取基于线程的客户端套接字创建套接字客户端创建客户端套接字创建非将文本写入套接字从套接字读取文本当一个非使用套接字发送POST请求使用套接字创建套接字客户端验证端口值是否在范围(1)内通过Socket获取服务器数据的方法使用套接字获取服务器状态检查特定的套接字端口是否可用。查找空闲端口从套接字读取简单文件套接字客户端从服务器读取消息从web读取html文件在SecureClient/Server中完成密钥交换,不在本地进行套接字通信从客户端接收RSA非对称公钥,生成AES对称密钥带校验和的套接字使用套接字发送消息