使用TCP协议实现客户端和服务器数据传输
程序员文章站
2024-03-22 15:00:40
...
/*客户端和服务端互访,传输字节流*/
import java.net.*;
import java.io.*;
class TCPClient2
{
public static void main(String[] args) throws Exception
{
Socket s=new Socket ("192.168.191.1",10004);
OutputStream out=s.getOutputStream();
out.write("server nihao".getBytes());
InputStream in=s.getInputStream();
byte[] buf=new byte[1024];
int len=in.read(buf);
System.out.println(new String (buf,0,len));
s.close();
}
}
class TCPServer2
{
public static void main(String[] args) throws Exception
{
ServerSocket ss=new ServerSocket(10004);
Socket s=ss.accept();
String ip=s.getInetAddress().getHostAddress();
System.out.println(ip+"...connected");
InputStream in=s.getInputStream();
byte[] buf=new byte[1024];
int len=in.read(buf);
System.out.println(new String (buf,0,len));
OutputStream out=s.getOutputStream();
Thread.sleep(10000);
out.write("shoudao dajiahao".getBytes());
s.close();
}
}
/*
建立文本转换服务器:
客户端发送文本给服务器,服务器将文本转换成大写返回给服务端
客户端可以不断进行文本转换,输入over时结束
*/
/*
客户端:IO技术
源:键盘录入
目的:网络输出流
操作的是文本数据,可以选择字符流
步骤:
1,建立服务
2,获取键盘录入
3,将数据发给服务端
4,获取服务端返回的大写数据
5,结束,关资源
*/
import java.io.*;
import java.net.*;
class TransClient
{
public static void main(String[] args) throws Exception
{
Socket s=new Socket ("219.245.124.44",10005);
//读取键盘数据,用转换流将System.in读取的键盘得到的字节流转换为字符流
BufferedReader bufr=new BufferedReader(new InputStreamReader(System.in));
//将数据写入到socket输出流,发给服务端
BufferedWriter bufOut=new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
//socket读取流,读取服务端返回的数据
BufferedReader bufIn=new BufferedReader(new InputStreamReader(s.getInputStream()));
String line=null;
while((line=bufr.readLine())!=null){
if("over".equals(line))
break;
bufOut.write(line);
bufOut.newLine();
bufOut.flush();
String str=bufIn.readLine();
System.out.println("server:"+str);
}
bufr.close();
s.close();
}
}
/*
服务端:
源:socket读取流
目的:socket输出流
*/
class TransServer
{
public static void main(String[] args) throws Exception
{
ServerSocket ss=new ServerSocket(10005);
Socket s=ss.accept();
String ip=s.getInetAddress().getHostAddress();
System.out.println(ip+"...connected");
BufferedReader bufIn=
new BufferedReader(new InputStreamReader(s.getInputStream()));
BufferedWriter bufOut=
new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
String line=null;
while((line=bufIn.readLine())!=null){
bufOut.write(line.toUpperCase());
bufOut.newLine();
bufOut.flush();
}
s.close();
ss.close();
}
}
下一篇: leetcode 67 二进制求和