//利用TCP来发送文本文件,服务端将文本转换成大写返回客户端源代码:
//客户端:
import java.io.*;
import java.net.*;
class TransClient
{
public static void main(String[] args) throws Exception
{
//建立TCP客户端的Socket,标识服务端IP地址和端口号
Socket s = new Socket("192.168.1.109",10005);
//定义读取键盘数据的流对象
BufferedReader bufr =
new BufferedReader(new InputStreamReader(System.in));
//定义目的,将数据写入到socket输出流,发给服务端
BufferedWriter bufOut =
newBufferedWriter(newOutputStreamWriter
(s.getOutputStream()));
//定义一个Socket读取流,读取服务端返回的大写信息
BufferedReader bufIn =
new BufferedReader(new InputStreamReader
(s.getInputStream()));
String line = null;
while((line=bufr.readLine())!=null)
{
//结束标示“over”,循环结束,发送结束
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();
}
}
//服务端:
import java.io.*;
import java.net.*;
class TransServer
{
public static void main(String[] args) throws Exception
{
//建立TCP服务端的ServerSocket,标识端口号
ServerSocket ss = new ServerSocket(10005);
//通过ss获取客户端的Socket来传输数据以达到连接效果
Socket s = ss.accept();
String ip = s.getInetAddress().getHostAddress();
System.out.println(ip+"....connected");
//读取socket读取流中的数据
BufferedReader bufIn =
new BufferedReader(new InputStreamReader
(s.getInputStream()));
//目的。socket输出流。将大写数据写入到socket输出流,并发送给客户端。
BufferedWriter bufOut =
new BufferedWriter(new OutputStreamWriter
(s.getOutputStream()));
String line = null;
while((line=bufIn.readLine())!=null)
{
System.out.println(line);
//将读取的字符转换成大写的
bufOut.write(line.toUpperCase());
bufOut.newLine();
bufOut.flush();
}
s.close();
ss.close();
}
}
|
|