00001 /*************************************************************************** 00002 *cr 00003 *cr (C) Copyright 1995-2019 The Board of Trustees of the 00004 *cr University of Illinois 00005 *cr All Rights Reserved 00006 *cr 00007 ***************************************************************************/ 00008 00009 /*************************************************************************** 00010 * RCS INFORMATION: 00011 * 00012 * $RCSfile: IMDSim.C,v $ 00013 * $Author: johns $ $Locker: $ $State: Exp $ 00014 * $Revision: 1.32 $ $Date: 2019/01/17 21:20:59 $ 00015 * 00016 *************************************************************************** 00017 * DESCRIPTION: 00018 * Routines to manage the low-level setup and teardown of Interactive MD 00019 * simulations. 00020 ***************************************************************************/ 00021 00022 #include <stdlib.h> 00023 #include "IMDSim.h" 00024 #include "vmdsock.h" 00025 #include "IMDMgr.h" 00026 #include "Inform.h" 00027 00028 IMDSim::IMDSim(const char *host, int port) { 00029 00030 new_coords_ready = 0; 00031 numcoords = 0; 00032 simstate = IMDOFFLINE; 00033 00034 vmdsock_init(); // make sure Winsock interfaces are initialized 00035 sock = vmdsock_create(); 00036 if (sock == NULL) { 00037 msgErr << "Error connecting: could not create socket" << sendmsg; 00038 return; 00039 } 00040 int rc = vmdsock_connect(sock, host, port); 00041 if (rc < 0) { 00042 msgErr << "Error connecting to " << host << " on port "<< port <<sendmsg; 00043 vmdsock_destroy(sock); 00044 sock = 0; 00045 return; 00046 } 00047 handshake(); 00048 simstate = IMDRUNNING; 00049 } 00050 00051 void IMDSim::disconnect() { 00052 simstate = IMDOFFLINE; 00053 if (sock) { 00054 imd_disconnect(sock); 00055 vmdsock_shutdown(sock); 00056 vmdsock_destroy(sock); 00057 sock = 0; 00058 } 00059 } 00060 00061 IMDSim::~IMDSim() { 00062 disconnect(); 00063 } 00064 00065 // Handshake: currently this is a 'one-way' handshake: after VMD connects, 00066 // NAMD sends to VMD an integer 1 in the length field of the header, without 00067 // converting network byte orer. 00068 00069 void IMDSim::handshake() { 00070 00071 need2flip = imd_recv_handshake(sock); 00072 switch (need2flip) { 00073 case 0: 00074 msgInfo << "Connected to same-endian machine" << sendmsg; 00075 break; 00076 case 1: 00077 msgInfo << "Connected to opposite-endian machine" << sendmsg; 00078 break; 00079 default: 00080 msgErr << "Unable to ascertain relative endianness of remote machine" 00081 << sendmsg; 00082 disconnect(); 00083 } 00084 } 00085 00086 /* Only works with aligned 4-byte quantities, will cause a bus error */ 00087 /* on some platforms if used on unaligned data. */ 00088 void IMDSim::swap4_aligned(void *v, long ndata) { 00089 int *data = (int *) v; 00090 long i; 00091 int *N; 00092 for (i=0; i<ndata; i++) { 00093 N = data + i; 00094 *N=(((*N>>24)&0xff) | ((*N&0xff)<<24) | 00095 ((*N>>8)&0xff00) | ((*N&0xff00)<<8)); 00096 } 00097 } 00098