Java TCP通信:模拟服务器与客户端
首先是服务器端的代码:
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Tcpserver {
public static void main(String[] args) {
try {
ServerSocket ss = new ServerSocket(8889); //指定端口,服务器与客户端要一致
while (true) {
Socket socket = ss.accept(); //等待客户端的接入
System.out.println("the server is listening---" + socket);
System.out.println("服务器端读取数据");
InputStream is = socket.getInputStream(); //建立输入流,读取来自客户端的数据
byte[] bytes = new byte[1024]; //字节流,所以用byte数组存储
int len = 0;
String str = null;
while ((len = is.read(bytes)) != -1) {
str = new String(bytes, 0, len);
System.out.println(str);
}
socket.shutdownInput(); //关闭输入
//String str = "hello world";
str = "I have received:" + str;
OutputStream os = socket.getOutputStream(); //建立字节输出流,将反馈信息发送给客户端
os.write(str.getBytes()); //同样是要用字节的方式
System.out.println("服务端写出数据完毕!");
socket.shutdownOutput();
os.close();
is.close();
socket.close();
if (str.compareTo("quit") == 0)
break;
}
System.out.println("the server will quit...");
ss.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
客户端:
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class Tcpclient {
public static void main(String[] args) {
try {
Scanner cin = new Scanner(System.in);
Socket socket=new Socket(InetAddress.getLocalHost(),8889); //连接服务器,通过TCP/IP,指定端口号
System.out.println("客户端:"+socket);
String data= new String();
String stop = "quit";
data = cin.next();
OutputStream os = socket.getOutputStream(); //建立字节输出流
os.write(data.getBytes()); //将输入的内容发送给服务器
System.out.println("键盘输入数据,客户端写出数据完毕!");
socket.shutdownOutput();
System.out.println("客户端读取数据");
InputStream is = socket.getInputStream(); //建立字节输入流
byte[] bytes=new byte[1024];
int len=0;
String str=null;
while((len=is.read(bytes))!=-1)
{
str=new String(bytes,0,len);
System.out.println(str);
}
socket.shutdownInput();
is.close(); //关闭所有的通道
os.close();
socket.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
还没有评论,来说两句吧...