Socket通信-基于TCP之客户端
import java.net.*;
import java.io.*;
import java.util.*;
class QQChatClient
{
public static void main(String[] args)
{
//System.out.println("Hello World!");
try{
// 1. 向服务器发送请求连接
Socket s = new Socket("10.8.160.31", 8888);
try{
//向服务器发送消息
OutputStream out = s.getOutputStream();
// 接收服务器来自消息
InputStream in = s.getInputStream();
// 键盘录入信息
Scanner scan = new Scanner(System.in);
while(true){
System.out.println("向服务器发送信息:");
String send = scan.nextLine();
out.write(send.getBytes());
// 读取服务端发送过来的信息
byte[] b = new byte[in.available()];
int len = in.read(b);
System.out.println("来自于服务器的消息:" + new String(b, 0, len));
}
}finally{
s.close();
}
}catch(IOException e){
e.printStackTrace();
}
}
}