初学Socket。
写个简单的Client,Server聊天程序,从一个更简单的程序修改过来的,Enjoying。
东西不大,但是基础的东西涉及到了一些。
客户端能够连接上,断开,再连接。(被我修改的那个不能断开,也就不能重连了)
缺陷:在服务器上保存了所有的链接,更进一步改进应该处理好客户端连接的缓存和断开的关系。
Server 存储的信息
package practice;
import java.net.*;
import java.io.*;
public class ClientInfo {
private Socket socket;
private PrintWriter writer;
private BufferedReader reader;
private String clientIp;
private int clientPort;
public String getClientIp() {
return clientIp;
}
public void setClientIp(String clientIp) {
this.clientIp = clientIp;
}
public int getClientPort() {
return clientPort;
}
public void setClientPort(int clientPort) {
this.clientPort = clientPort;
}
public Socket getSocket() {
return socket;
}
public void setSocket(Socket socket) {
this.socket = socket;
}
public PrintWriter getWriter() {
return writer;
}
public void setWriter(PrintWriter writer) {
this.writer = writer;
}
public BufferedReader getReader() {
return reader;
}
public void setReader(BufferedReader reader) {
this.reader = reader;
}
public void closeSocket(){
try{
reader.close();
writer.close();
socket.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
Server
package practice;
import java.net.*;
import java.io.*;
import java.util.*;
public class VerySimpleChatServer {
ArrayList<ClientInfo> clientInfoList;
public static void main(String[] args){
(new VerySimpleChatServer()).go();
}
private void go(){
clientInfoList = new ArrayList<ClientInfo>();
try{
ServerSocket serverSocket = new ServerSocket(5000);
while(true){
Socket newSocket = serverSocket.accept();
ClientInfo client = new ClientInfo();
client.setClientIp(newSocket.getInetAddress().getHostAddress());
client.setClientPort(newSocket.getPort());
client.setSocket(newSocket);
client.setWriter(new PrintWriter(newSocket.getOutputStream()));
client.setReader(new BufferedReader(new InputStreamReader(newSocket.getInputStream())));
clientInfoList.add(client);
Thread t = new Thread(new ThreadRunner(client));
t.start();
System.out.println("got a new connection!");
}
}catch(Exception e){
e.printStackTrace();
}
}
class ThreadRunner implements Runnable{
ClientInfo clientInfo;
public ThreadRunner(ClientInfo clientInfo){
try{
this.clientInfo = clientInfo;
}catch(Exception e){
e.printStackTrace();
}
}
public void run(){
String message = null;
try{
while((message = clientInfo.getReader().readLine()) != null){
System.out.println("received message: " + message);
tellEveryBody(message);
}
}catch(Exception e){
//e.printStackTrace();
synchronized(this){
clientInfo.closeSocket();
clientInfoList.remove(clientInfo);
}
}
}
}
private void tellEveryBody(String message){
for(ClientInfo client: clientInfoList){
try{
PrintWriter writer = client.getWriter();
System.out.println("tell "+ client.getClientIp()+":" + client.getClientPort() +" about: " + message);
writer.println(message);
writer.flush();
}catch(Exception e){
e.printStackTrace();
}
}// end for
}// end tellEveryBody
}
Client
package practice;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class SimpleChatClient {
JTextField outgoing;
JTextArea incoming;
PrintWriter writer;
BufferedReader reader;
Socket socket;
/**
* @param args
*/
public static void main(String[] args) {
(new SimpleChatClient()).go();
}
private void go(){
buildGUI();
if(initSocket()){
initWriter();
initReader();
startReadThread();
}
}
private void buildGUI(){
JFrame frame = new JFrame("Simple Chat Client!");
JPanel panel = new JPanel();
outgoing = new JTextField(20);
incoming = new JTextArea(15,30);
incoming.setLineWrap(true);
incoming.setWrapStyleWord(true);
incoming.setEditable(false);
JScrollPane inScroller = new JScrollPane(incoming);
inScroller.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
inScroller.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
JButton send = new JButton("Send");
send.addActionListener(new SendActionListener());
panel.add(inScroller);
panel.add(outgoing);
panel.add(send);
frame.getContentPane().add(panel);
frame.setSize(400,360);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
private boolean initSocket(){
try{
socket = new Socket("127.0.0.1",5000);
}catch(Exception e){
e.printStackTrace();
return false;
}
return true;
}
private void initWriter(){
try{
writer = new PrintWriter(socket.getOutputStream());
}catch(Exception e){
e.printStackTrace();
}
}
private void initReader(){
try{
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
}catch(Exception e){
e.printStackTrace();
}
}
private void startReadThread(){
Thread t = new Thread(new ReadRunner());
t.start();
}
private void sendMessage(String message){
try{
writer.println(message);
writer.flush();
outgoing.setText("");
outgoing.requestFocus();
}catch(Exception e){
e.printStackTrace();
}
}
class SendActionListener implements ActionListener{
public void actionPerformed(ActionEvent event){
sendMessage(outgoing.getText());
}
}
class ReadRunner implements Runnable{
public void run(){
String line = "";
try{
while((line = reader.readLine())!=null){
System.out.println("Receive from server: " + line);
incoming.append("Receive from server: " + line + " ");
}
}catch(Exception e){
e.printStackTrace();
}
}
}
public void finalize(){
try{
reader.close();
writer.close();
socket.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
相关文章
- java.lang.RuntimeException: com.netflix.client.ClientException: Load balancer does not have available server for client: service-one
- 从头写个http client(java)
- Java网络编程以及简单的聊天程序
- Java: 写个简单的Client,Server聊天程序
- C++程序员学Java系列之三五:一个简易的Client,Server样例
- 7.Java NIO系列教程之Server/Client完整示例
- Java 默认/缺省 server 还是 client 模式
- java NIO Server 和 Client简单样例
- Java虚拟机JVM之server模式与client模式的区别