📄 clientchat.java~38~
字号:
package chattingroom;
import java.io.*;
import java.net.*;
import javax.swing.JOptionPane;
/**
* <p>Title: </p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2004</p>
* <p>Company: </p>
* @author not attributable
* @version 1.0
*/
public class ClientChat {
PrintWriter outputstream; //输出流(指向服务器)
BufferedReader inputstream;//输入流(来自服务器)
String clientRequest;//客户端请求
String severResponse;//服务器端回应
static boolean connected=false;
static InetAddress ServerHost;
Socket clientSocket=null;
public ClientChat() {
}
public ClientChat(String serverName,int port)
{
try{
ServerHost=InetAddress.getByName(serverName);
clientSocket=new Socket(serverName,port ); //根据服务器主机名或IP在指定端口建立连接
outputstream=new PrintWriter(new OutputStreamWriter(clientSocket.getOutputStream()),true);//获得Socket的输出流
inputstream=new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));//获得Socket的输入流
}
catch(Exception e)
{JOptionPane.showMessageDialog(null,"无法连接服务器! 错误:"+e.getMessage(),"系统提示信息",1);}
if (clientSocket.isConnected())
{connected=true;}
JOptionPane.showMessageDialog(null,"已成功地连接到服务器,您可以开始发言了!","系统提示信息",1);
}
public void sendRequest(String request)
{
outputstream.println(request); //向Socket的输出流写入字符串
outputstream.flush();
}
public String getResponse()
{String str=new String("");
try{
str=inputstream.readLine(); //从Socket的输入流读入字符串
}
catch(IOException e){JOptionPane.showMessageDialog(null,"无法从服务器读取消息!","系统提示信息",1); }//必须捕获错误
return str;}
public void close(){
try {
clientSocket.close();
}
catch (IOException ex) {
JOptionPane.showMessageDialog(null,"与服务器断开连接出错: "+ex.getMessage(),"系统提示信息",1); //必须捕获错误
}
}
public static void main(String[] args) {
ClientChat clientChat1 = new ClientChat();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -