一、入门
要想学习socket通讯,首先得知道tcp/ip和udp连接,具体可参考浅谈TCP/IP 和 UDP的区别
二、示例
首先新建了一个java工程,包括两个部分,客户端SocketClient类和服务器端SocketServer类,服务器端SocketServer监听3756端口,客户端SocketClient往服务器端的3756端口发送一些文本信息,服务器端SocketServer接受完客户端的信息后,将客户端的信息打印出来。
服务器端SocketServer:
package GPS;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter; import java.net.ServerSocket;
import java.net.Socket; public class SocketServer {
public static void main(String [] args){
ServerSocket ss = null;
BufferedReader br = null;
Socket sk = null;
try{
System.out.println("create server socket....");
ss = new ServerSocket(3756);
System.out.println("wait for a connection....");
while(true) //服务器端一直监听这个端口,等待客户端的连接
{
sk = ss.accept();
System.out.println("get a socket object...");
br = new BufferedReader(new InputStreamReader(sk.getInputStream()));
String line = null;
while((line = br.readLine()) != null){
System.out.println(line); //服务器端打印客户端发送的信息数据
}
}
}
catch(Exception ex){
System.out.println(ex.getMessage());
}
finally{
try{
if(br != null){
br.close();
}
if(ss != null){
ss.close();
}
if(sk != null){
sk.close();
}
}
catch(Exception ex){
System.out.println(ex.getMessage());
}
}
} }
客户端SocketClient:
package GPS;
import java.io.BufferedInputStream;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date; public class SocketClient {
public static void main(String [] args){
Socket sk = null;
PrintWriter pw = null;
try{
sk = new Socket("localhost",3756);
pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(sk.getOutputStream())));
while(true)
{
Thread.sleep(3000);
pw.println("I come from client"); //客户端往服务器端发送数据
pw.flush();
}
}
catch(Exception ex){
System.out.println(ex.getMessage());
}
finally{
try{
if(sk != null){
sk.close();
}
if(pw != null){
pw.close();
}
}
catch(Exception ex){
System.out.println(ex.getMessage());
}
}
} }
三、运行
首先启动服务器端SocketServer,然后运行客户端类SocketClient,服务端每隔3秒就会收到客户端发送来的信息:I come from client
create server socket....
wait for a connection....
get a socket object...
I come from client
这样就完成了一次socket连接请求,原理很简单,服务器端监听某一个端口,客户端向服务器端的指定端口请求连接,连接成功后,发送socket数据,服务器端接收并打印输出