本人最近在项目中使用到了socket 通信,以前一直没写过,在网上找了很多资料觉得都写得比较复杂,我后来自己写了一个现在拿出来分享。我写的socket并没有使用线程安全,只是个简单的Server和Client,希望对初学者有点帮助。呵呵! 下面是实现:
Server.java类的实现。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
private ServerSocket server;
private Socket socket;
private BufferedReader in;
private PrintWriter out;
public static final String IP = "127.0.0.1";//这里是IP地址,这个地址可以随便修改(该为你自己的IP)
public static final int PORT = 3333;//这里是设置server的端口号
public void startServer(){
try {
server = new ServerSocket(Server.PORT);
int i = 1 , j = 1;
while (true) {
System.out.println("Server listen in Client Request! ");
socket = server.accept();
in = new BufferedReader(new InputStreamReader(socket
.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);
String line = in.readLine();
System.out.println("Server get Client send " + i++ + " message:"+line);
out.print("this Server return Client " + j++ + " message:" + line);
out.close();
in.close();
socket.close();
}
} catch (IOException e) {
e.printStackTrace();
try {
socket.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
public static void main(String[] args) throws IOException {
Server server = new Server();
server.startServer();
}
}
这里是Client.java的实现:
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
public class Client {
private Socket socket;
public void sendMessage(String message) {
try {
//这里初始化Socket 要提供两个参数 server的IP 和 port
socket = new Socket(Server.IP, Server.PORT);
socket.setSoTimeout(60000);
// send message
PrintWriter ps = new PrintWriter(new OutputStreamWriter(
new BufferedOutputStream(socket.getOutputStream()), "GBK"),
true);
// must use println();
ps.println(message);
// read server return message
BufferedReader br = new BufferedReader(new InputStreamReader(socket
.getInputStream(), "GBK"));
StringBuffer sbf = new StringBuffer();
String str = null;
int i = 1;
while ((str = br.readLine()) != null) {
sbf.append(str);
System.out.println("Server return " + i++ + " message: "
+ sbf.toString());
}
br.close();
} catch (Exception e) {
e.printStackTrace();
try {
socket.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
public static void main(String[] args) {
Client client = new Client();
client.sendMessage("first socket!");
}
}
好了!简单的socket就实现了,高手看了别笑话就可以了!