关于JAVA SOCKET编程
请问在JAVA中是通过什么方式实现SOCKET编程的?我看了个例子,上面这样写的:
out = new PrintWriter(socket.getOutputStream(),true);
out.println(str);
JAVA中SOCKET编程发送数据的实现方法后面的STRING类型,难道我只能把组合好的BYTE[]转成STRING发送出去吗?这样对吗?
------解决方案--------------------ObjectOutputStream 可以发送String
------解决方案--------------------PrintWriter是包装过的OutputStream,你直接用Outputstream就是发送byte的。
(初学JAVA,还是等高手来确定下)
------解决方案--------------------这是一个用Socket建立个最简单的聊天程序Java、Socket、网络编程、聊天
/*一个作为Server*/
import java.io.*;
import java.net.*;
public class MyServer{
public static void main(String[] args)
throws
IOException{
ServerSocket s=new ServerSocket(8658);
System.out.println( "开始: "+s);
try{
Socket socket=s.accept();
try{
System.out.println( "连接接受 "+socket);
BufferedReader in=new BufferedReader(new InputStreamReader
(socket.getInputStream()));
PrintWriter out=new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),true);
while(true){
String str=in.readLine();
if(str.equals( "q ")) break;
System.out.println( "对方说: "+str);
BufferedReader is=new BufferedReader(new InputStreamReader(System.in));
String input=new String();
input=is.readLine().trim();
out.println(input);
System.out.print( "我说: ");
out.flush();
}
}
finally{
System.out.println( "关闭.... ");
socket.close();
}
}
finally{
s.close();
}
}
}
/*一个作为Client*/
import java.io.*;
import java.net.*;
public class MyClient{
public static void main(String[] args)
throws IOException{
InetAddress addr=InetAddress.getByName( "127.0.0.1 ");
System.out.println( "地址= "+addr);
Socket socket=new Socket(addr,8658);
try{
System.out.println( "socket= "+socket);
BufferedReader is=new BufferedReader(new InputStreamReader(System.in));
PrintWriter out=new PrintWriter(socket.getOutputStream(),true);
for(;;){
System.out.print( "我说: ");
String input=new String();
input=is.readLine().trim();
out.println(input);
if(input.equals( "q ")) break;
BufferedReader in=new BufferedReader(new InputStreamReader
(socket.getInputStream()));
String str=in.readLine();
System.out.println( "对方说: "+str);
out.flush();
}
}
finally{
System.out.println( "关闭 ");
socket.close();
}
}
}
------解决方案--------------------socket.getOutputStream(),这个是从Socket返回的字节流,
在这个基础上,你可以包装任意的输出流类,来实现你需要的功能,
传送字节数组,
DataOutputStream类
write(byte[] b, int off, int len)
将指定字节数组中从偏移量 off 开始的 len 个字节写入基础输出流。