Java TCP通信使用的是Socket(客服端)和ServerSocket(服务端),具体代码如下。
server端代码:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket; public class TcpService {
public static void main(String[] args) throws Exception {
//建立服务器端ServerSocket对象只需绑定一个端口
ServerSocket listen = new ServerSocket();
Socket client = null;
Boolean flag = true;
while(flag){
System.out.println("Server-->: ");
client = listen.accept();//通过accept()方法得到连接到次服务器端口对应的客服端Socket
new Thread(new ThreadServer(client)).start();
} listen.close();
}
}
class ThreadServer implements Runnable{
private Socket client; public ThreadServer(Socket client){
this.client = client;
} @Override
public void run() {
BufferedReader buf = null;
PrintStream out = null;
try{
out = new PrintStream(this.client.getOutputStream());
buf = new BufferedReader(new InputStreamReader(this.client.getInputStream())); boolean flag = true;
while(flag){
String str = buf.readLine(); if(null == str){
flag = false;
}else{
if("bye".equals(str)){
flag = false;
}else{
str = "Respone to client by server:" + str + "\n";out.write(str.getBytes());
}
}
}
this.client.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
Client端代码:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket; public class TcpClient {
public static void main(String[] args)throws IOException{
//建立客服端Socket,需写入服务器端主机地址以及服务端口
Socket client = new Socket("localhost",9999);
BufferedReader buf = null;
PrintStream out = null;
BufferedReader input = null;
//键盘录入
input = new BufferedReader(new InputStreamReader(System.in));
//从服务器端得到的输入流
buf = new BufferedReader(new InputStreamReader(client.getInputStream()));
//输出
out = new PrintStream(client.getOutputStream());
//建立标志,用于判断结束会话
boolean flag = true;
while(flag){
System.out.print("Input:");
String str = input.readLine();
out.println(str); if("bye".equals(str)){
flag = false;
}else{
String echo = buf.readLine();
System.out.println(echo);
}
}
buf.close();
client.close();
}
}
测试:
需先将服务器端运行开启,之后才能运行客户端,结果如下:
服务器端:
Server-->:
Server-->:
客户端:
Input:hello world!
Respone to client by server:hello world!
Input: